<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="Docutils 0.8.1: http://docutils.sourceforge.net/" />
<title>libtorrent API Documentation</title>
<meta name="author" content="Arvid Norberg, arvid&#64;rasterbar.com" />
<link rel="stylesheet" type="text/css" href="../../css/base.css" />
<link rel="stylesheet" type="text/css" href="../../css/rst.css" />
<script type="text/javascript">
/* <![CDATA[ */
    (function() {
        var s = document.createElement('script'), t = document.getElementsByTagName('script')[0];
        s.type = 'text/javascript';
        s.async = true;
        s.src = 'http://api.flattr.com/js/0.6/load.js?mode=auto';
        t.parentNode.insertBefore(s, t);
    })();
/* ]]> */
</script>
<link rel="stylesheet" href="style.css" type="text/css" />
<style type="text/css">
/* Hides from IE-mac \*/
* html pre { height: 1%; }
/* End hide from IE-mac */
</style>
</head>
<body>
<div class="document" id="libtorrent-api-documentation">
    <div id="container">
    <div id="headerNav">
    <ul>
    <li class="first"><a href="/">Home</a></li>
    <li><a href="../../products.html">Products</a></li>
    <li><a href="../../contact.html">Contact</a></li>
    </ul>
    </div>
    <div id="header">
    <h1><span>Rasterbar Software</span></h1>
    <h2><span>Software developement and consulting</span></h2>
    </div>
    <div id="main">
<h1 class="title">libtorrent API Documentation</h1>
<table class="docinfo" frame="void" rules="none">
<col class="docinfo-name" />
<col class="docinfo-content" />
<tbody valign="top">
<tr><th class="docinfo-name">Author:</th>
<td>Arvid Norberg, <a class="last reference external" href="mailto:arvid&#64;rasterbar.com">arvid&#64;rasterbar.com</a></td></tr>
<tr><th class="docinfo-name">Version:</th>
<td>1.0.0</td></tr>
</tbody>
</table>
<div class="contents topic" id="table-of-contents">
<p class="topic-title first">Table of contents</p>
<ul class="simple">
<li><a class="reference internal" href="#overview" id="id13">overview</a></li>
<li><a class="reference internal" href="#things-to-keep-in-mind" id="id14">things to keep in mind</a></li>
<li><a class="reference internal" href="#network-primitives" id="id15">network primitives</a></li>
<li><a class="reference internal" href="#session" id="id16">session</a></li>
<li><a class="reference internal" href="#entry" id="id17">entry</a></li>
<li><a class="reference internal" href="#torrent-info" id="id18">torrent_info</a></li>
<li><a class="reference internal" href="#torrent-handle" id="id19">torrent_handle</a></li>
<li><a class="reference internal" href="#torrent-status" id="id20">torrent_status</a></li>
<li><a class="reference internal" href="#peer-info" id="id21">peer_info</a></li>
<li><a class="reference internal" href="#feed-handle" id="id22">feed_handle</a></li>
<li><a class="reference internal" href="#feed-item" id="id23">feed_item</a></li>
<li><a class="reference internal" href="#session-customization" id="id24">session customization</a></li>
<li><a class="reference internal" href="#pe-settings" id="id25">pe_settings</a></li>
<li><a class="reference internal" href="#proxy-settings" id="id26">proxy_settings</a></li>
<li><a class="reference internal" href="#ip-filter" id="id27">ip_filter</a></li>
<li><a class="reference internal" href="#big-number" id="id28">big_number</a></li>
<li><a class="reference internal" href="#bitfield" id="id29">bitfield</a></li>
<li><a class="reference internal" href="#hasher" id="id30">hasher</a></li>
<li><a class="reference internal" href="#fingerprint" id="id31">fingerprint</a></li>
<li><a class="reference internal" href="#upnp-and-nat-pmp" id="id32">UPnP and NAT-PMP</a></li>
<li><a class="reference internal" href="#free-functions" id="id33">free functions</a></li>
<li><a class="reference internal" href="#alerts" id="id34">alerts</a></li>
<li><a class="reference internal" href="#alert-dispatcher" id="id35">alert dispatcher</a></li>
<li><a class="reference internal" href="#exceptions" id="id36">exceptions</a></li>
<li><a class="reference internal" href="#error-code" id="id37">error_code</a></li>
<li><a class="reference internal" href="#storage-interface" id="id38">storage_interface</a></li>
<li><a class="reference internal" href="#magnet-links" id="id39">magnet links</a></li>
<li><a class="reference internal" href="#queuing" id="id40">queuing</a></li>
<li><a class="reference internal" href="#fast-resume" id="id41">fast resume</a></li>
<li><a class="reference internal" href="#storage-allocation" id="id42">storage allocation</a></li>
<li><a class="reference internal" href="#extensions" id="id43">extensions</a></li>
<li><a class="reference internal" href="#piece-picker" id="id44">piece picker</a></li>
<li><a class="reference internal" href="#ssl-torrents" id="id45">SSL torrents</a></li>
</ul>
</div>
<div class="section" id="overview">
<h1>overview</h1>
<p>The interface of libtorrent consists of a few classes. The main class is
the <tt class="docutils literal">session</tt>, it contains the main loop that serves all torrents.</p>
<p>The basic usage is as follows:</p>
<ul>
<li><p class="first">construct a session</p>
</li>
<li><p class="first">load session state from settings file (see <a class="reference internal" href="#load-state-save-state">load_state() save_state()</a>)</p>
</li>
<li><p class="first">start extensions (see <a class="reference internal" href="#add-extension">add_extension()</a>).</p>
</li>
<li><p class="first">start DHT, LSD, UPnP, NAT-PMP etc (see <a class="reference internal" href="#start-dht-stop-dht-set-dht-settings-dht-state-is-dht-running">start_dht() stop_dht() set_dht_settings() dht_state() is_dht_running()</a>
<a class="reference internal" href="#start-lsd-stop-lsd">start_lsd() stop_lsd()</a>, <a class="reference internal" href="#start-upnp-stop-upnp">start_upnp() stop_upnp()</a> and <a class="reference internal" href="#start-natpmp-stop-natpmp">start_natpmp() stop_natpmp()</a>)</p>
</li>
<li><p class="first">parse .torrent-files and add them to the session (see <a class="reference internal" href="#bdecode-bencode">bdecode() bencode()</a> and <a class="reference internal" href="#async-add-torrent-add-torrent">async_add_torrent() add_torrent()</a>)</p>
</li>
<li><p class="first">main loop (see <a class="reference internal" href="#session">session</a>)</p>
<blockquote>
<ul class="simple">
<li>query the torrent_handles for progress (see <a class="reference internal" href="#torrent-handle">torrent_handle</a>)</li>
<li>query the session for information</li>
<li>add and remove torrents from the session at run-time</li>
</ul>
</blockquote>
</li>
<li><p class="first">save resume data for all torrent_handles (optional, see
<a class="reference internal" href="#save-resume-data">save_resume_data()</a>)</p>
</li>
<li><p class="first">save session state (see <a class="reference internal" href="#load-state-save-state">load_state() save_state()</a>)</p>
</li>
<li><p class="first">destruct session object</p>
</li>
</ul>
<p>Each class and function is described in this manual.</p>
<p>For a description on how to create torrent files, see <a class="reference external" href="make_torrent.html">make_torrent</a>.</p>
</div>
<div class="section" id="things-to-keep-in-mind">
<h1>things to keep in mind</h1>
<p>A common problem developers are facing is torrents stopping without explanation.
Here is a description on which conditions libtorrent will stop your torrents,
how to find out about it and what to do about it.</p>
<p>Make sure to keep track of the paused state, the error state and the upload
mode of your torrents. By default, torrents are auto-managed, which means
libtorrent will pause them, unpause them, scrape them and take them out
of upload-mode automatically.</p>
<p>Whenever a torrent encounters a fatal error, it will be stopped, and the
<tt class="docutils literal"><span class="pre">torrent_status::error</span></tt> will describe the error that caused it. If a torrent
is auto managed, it is scraped periodically and paused or resumed based on
the number of downloaders per seed. This will effectively seed torrents that
are in the greatest need of seeds.</p>
<p>If a torrent hits a disk write error, it will be put into upload mode. This
means it will not download anything, but only upload. The assumption is that
the write error is caused by a full disk or write permission errors. If the
torrent is auto-managed, it will periodically be taken out of the upload
mode, trying to write things to the disk again. This means torrent will recover
from certain disk errors if the problem is resolved. If the torrent is not
auto managed, you have to call <a class="reference internal" href="#set-upload-mode">set_upload_mode()</a> to turn
downloading back on again.</p>
</div>
<div class="section" id="network-primitives">
<h1>network primitives</h1>
<p>There are a few typedefs in the <tt class="docutils literal">libtorrent</tt> namespace which pulls
in network types from the <tt class="docutils literal">asio</tt> namespace. These are:</p>
<pre class="literal-block">
typedef asio::ip::address address;
typedef asio::ip::address_v4 address_v4;
typedef asio::ip::address_v6 address_v6;
using asio::ip::tcp;
using asio::ip::udp;
</pre>
<p>These are declared in the <tt class="docutils literal">&lt;libtorrent/socket.hpp&gt;</tt> header.</p>
<p>The <tt class="docutils literal">using</tt> statements will give easy access to:</p>
<pre class="literal-block">
tcp::endpoint
udp::endpoint
</pre>
<p>Which are the endpoint types used in libtorrent. An endpoint is an address
with an associated port.</p>
<p>For documentation on these types, please refer to the <a class="reference external" href="http://asio.sourceforge.net/asio-0.3.8/doc/asio/reference.html">asio documentation</a>.</p>
</div>
<div class="section" id="session">
<h1>session</h1>
<p>The <tt class="docutils literal">session</tt> class has the following synopsis:</p>
<pre class="literal-block">
class session: public boost::noncopyable
{

        session(fingerprint const&amp; print
                = libtorrent::fingerprint(
                &quot;LT&quot;, 0, 1, 0, 0)
                , int flags = start_default_features
                        | add_default_plugins
                , int alert_mask = alert::error_notification);

        session(
                fingerprint const&amp; print
                , std::pair&lt;int, int&gt; listen_port_range
                , char const* listen_interface = 0
                , int flags = start_default_features
                        | add_default_plugins
                , int alert_mask = alert::error_notification);

        enum save_state_flags_t
        {
                save_settings = 0x001,
                save_dht_settings = 0x002,
                save_dht_state = 0x004,
                save_proxy = 0x008,
                save_i2p_proxy = 0x010,
                save_encryption_settings = 0x020,
                save_as_map = 0x040,
                save_feeds = 0x080,
        };

        void load_state(lazy_entry const&amp; e);
        void save_state(entry&amp; e, boost::uint32_t flags) const;

        torrent_handle add_torrent(
                add_torrent_params const&amp; params);
        torrent_handle add_torrent(
                add_torrent_params const&amp; params
                , error_code&amp; ec);

        void async_add_torrent(add_torrent_params const&amp; params);

        void pause();
        void resume();

        session_proxy abort();

        enum options_t
        {
                none = 0,
                delete_files = 1
        };

        enum session_flags_t
        {
                add_default_plugins = 1,
                start_default_features = 2
        };

        void remove_torrent(torrent_handle const&amp; h
                , int options = none);
        torrent_handle find_torrent(sha_hash const&amp; ih);

        std::vector&lt;torrent_handle&gt; get_torrents() const;
        void get_torrent_status(std::vector&lt;torrent_status&gt;* ret
                , boost::function&lt;bool(torrent_status const&amp;)&gt; const&amp; pred
                , boost::uint32_t flags = 0) const;
        void refresh_torrent_status(std::vector&lt;torrent_status&gt;* ret
                , boost::uint32_t flags) const;

        void set_settings(session_settings const&amp; settings);
        session_settings settings() const;
        void set_pe_settings(pe_settings const&amp; settings);

        void set_upload_rate_limit(int bytes_per_second);
        int upload_rate_limit() const;
        void set_download_rate_limit(int bytes_per_second);
        int download_rate_limit() const;

        void set_local_upload_rate_limit(int bytes_per_second);
        int local_upload_rate_limit() const;
        void set_local_download_rate_limit(int bytes_per_second);
        int local_download_rate_limit() const;

        void set_max_uploads(int limit);
        void set_max_connections(int limit);
        int max_connections() const;
        void set_max_half_open_connections(int limit);
        int max_half_open_connections() const;

        void set_proxy(proxy_settings const&amp; s);
        proxy_settings proxy() const;

        int num_uploads() const;
        int num_connections() const;

        void load_asnum_db(char const* file);
        void load_asnum_db(wchar_t const* file);
        void load_country_db(char const* file);
        void load_country_db(wchar_t const* file);
        int as_for_ip(address const&amp; adr);

        void set_ip_filter(ip_filter const&amp; f);
        ip_filter get_ip_filter() const;

        session_status status() const;
        cache_status get_cache_status() const;

        bool is_listening() const;
        unsigned short listen_port() const;

        enum {
                listen_reuse_address = 1,
                listen_no_system_port = 2
        };

        void listen_on(
                std::pair&lt;int, int&gt; const&amp; port_range
                , error_code&amp; ec
                , char const* interface = 0
                , int flags = 0);

        std::auto_ptr&lt;alert&gt; pop_alert();
        alert const* wait_for_alert(time_duration max_wait);
        void set_alert_mask(int m);
        size_t set_alert_queue_size_limit(
                size_t queue_size_limit_);
        void set_alert_dispatch(boost::function&lt;void(std::auto_ptr&lt;alert&gt;)&gt; const&amp; fun);

        feed_handle session::add_feed(feed_settings const&amp; feed);
        void session::remove_feed(feed_handle h);
        void session::get_feeds(std::vector&lt;feed_handle&gt;&amp; f) const;

        void add_extension(boost::function&lt;
                boost::shared_ptr&lt;torrent_plugin&gt;(torrent*)&gt; ext);

        void start_dht();
        void stop_dht();
        void set_dht_settings(
                dht_settings const&amp; settings);
        entry dht_state() const;
        void add_dht_node(std::pair&lt;std::string
                , int&gt; const&amp; node);
        void add_dht_router(std::pair&lt;std::string
                , int&gt; const&amp; node);
        bool is_dht_running() const;

        void start_lsd();
        void stop_lsd();

        upnp* start_upnp();
        void stop_upnp();

        natpmp* start_natpmp();
        void stop_natpmp();
};
</pre>
<p>Once it's created, the session object will spawn the main thread that will do all the work.
The main thread will be idle as long it doesn't have any torrents to participate in.</p>
<div class="section" id="id1">
<h2>session()</h2>
<blockquote>
<pre class="literal-block">
session(fingerprint const&amp; print
        = libtorrent::fingerprint(&quot;LT&quot;, 0, 1, 0, 0)
        , int flags = start_default_features
                | add_default_plugins
        , int alert_mask = alert::error_notification);

session(fingerprint const&amp; print
        , std::pair&lt;int, int&gt; listen_port_range
        , char const* listen_interface = 0
        , int flags = start_default_features
                | add_default_plugins
        , int alert_mask = alert::error_notification);
</pre>
</blockquote>
<p>If the fingerprint in the first overload is omited, the client will get a default
fingerprint stating the version of libtorrent. The fingerprint is a short string that will be
used in the peer-id to identify the client and the client's version. For more details see the
<a class="reference internal" href="#fingerprint">fingerprint</a> class. The constructor that only takes a fingerprint will not open a
listen port for the session, to get it running you'll have to call <tt class="docutils literal"><span class="pre">session::listen_on()</span></tt>.
The other constructor, that takes a port range and an interface as well as the fingerprint
will automatically try to listen on a port on the given interface. For more information about
the parameters, see <tt class="docutils literal">listen_on()</tt> function.</p>
<p>The flags paramater can be used to start default features (upnp &amp; nat-pmp) and default plugins
(ut_metadata, ut_pex and smart_ban). The default is to start those things. If you do not want
them to start, pass 0 as the flags parameter.</p>
<p>The <tt class="docutils literal">alert_mask</tt> is the same mask that you would send to <a class="reference internal" href="#set-alert-mask">set_alert_mask()</a>.</p>
</div>
<div class="section" id="id2">
<h2>~session()</h2>
<p>The destructor of session will notify all trackers that our torrents have been shut down.
If some trackers are down, they will time out. All this before the destructor of session
returns. So, it's advised that any kind of interface (such as windows) are closed before
destructing the session object. Because it can take a few second for it to finish. The
timeout can be set with <tt class="docutils literal">set_settings()</tt>.</p>
</div>
<div class="section" id="load-state-save-state">
<h2>load_state() save_state()</h2>
<blockquote>
<pre class="literal-block">
void load_state(lazy_entry const&amp; e);
void save_state(entry&amp; e, boost::uint32_t flags) const;
</pre>
</blockquote>
<p>loads and saves all session settings, including dht_settings, encryption settings and proxy
settings. <tt class="docutils literal">save_state</tt> writes all keys to the <tt class="docutils literal">entry</tt> that's passed in, which needs to
either not be initialized, or initialized as a dictionary.</p>
<p><tt class="docutils literal">load_state</tt> expects a <tt class="docutils literal">lazy_entry</tt> which can be built from a bencoded buffer with
<a class="reference internal" href="#lazy-bdecode">lazy_bdecode()</a>.</p>
<p>The <tt class="docutils literal">flags</tt> arguments passed in to <tt class="docutils literal">save_state</tt> can be used to filter which parts
of the session state to save. By default, all state is saved (except for the individual
torrents). These are the possible flags. A flag that's set, means those settings are saved:</p>
<pre class="literal-block">
enum save_state_flags_t
{
        save_settings =     0x001,
        save_dht_settings = 0x002,
        save_dht_state =    0x004,
        save_proxy =        0x008,
        save_i2p_proxy =    0x010,
        save_encryption_settings = 0x020,
        save_as_map =       0x040,
        save_feeds =        0x080
};
</pre>
</div>
<div class="section" id="pause-resume-is-paused">
<h2>pause() resume() is_paused()</h2>
<blockquote>
<pre class="literal-block">
void pause();
void resume();
bool is_paused() const;
</pre>
</blockquote>
<p>Pausing the session has the same effect as pausing every torrent in it, except that
torrents will not be resumed by the auto-manage mechanism. Resuming will restore the
torrents to their previous paused state. i.e. the session pause state is separate from
the torrent pause state. A torrent is inactive if it is paused or if the session is
paused.</p>
</div>
<div class="section" id="abort">
<h2>abort()</h2>
<blockquote>
<pre class="literal-block">
session_proxy abort();
</pre>
</blockquote>
<p>In case you want to destruct the session asynchrounously, you can request a session
destruction proxy. If you don't do this, the destructor of the session object will
block while the trackers are contacted. If you keep one <tt class="docutils literal">session_proxy</tt> to the
session when destructing it, the destructor will not block, but start to close down
the session, the destructor of the proxy will then synchronize the threads. So, the
destruction of the session is performed from the <tt class="docutils literal">session</tt> destructor call until the
<tt class="docutils literal">session_proxy</tt> destructor call. The <tt class="docutils literal">session_proxy</tt> does not have any operations
on it (since the session is being closed down, no operations are allowed on it). The
only valid operation is calling the destructor:</p>
<pre class="literal-block">
class session_proxy
{
public:
        session_proxy();
        ~session_proxy()
};
</pre>
</div>
<div class="section" id="async-add-torrent-add-torrent">
<h2>async_add_torrent() add_torrent()</h2>
<blockquote>
<pre class="literal-block">
typedef boost::function&lt;storage_interface*(file_storage const&amp;
        , file_storage const*, std::string const&amp;, file_pool&amp;
        , std::vector&lt;boost::uint8_t&gt; const&amp;) storage_constructor_type;

struct add_torrent_params
{
        add_torrent_params(storage_constructor_type s);

        enum flags_t
        {
                flag_seed_mode = 0x001,
                flag_override_resume_data = 0x002,
                flag_upload_mode = 0x004,
                flag_share_mode = 0x008,
                flag_apply_ip_filter = 0x010,
                flag_paused = 0x020,
                flag_auto_managed = 0x040.
                flag_duplicate_is_error = 0x080,
                flag_merge_resume_trackers = 0x100,
                flag_update_subscribe = 0x200,
                flag_super_seeding = 0x400,
                flag_sequential_download = 0x800
        };

        int version;
        boost::intrusive_ptr&lt;torrent_info&gt; ti;
#ifndef TORRENT_NO_DEPRECATE
        char const* tracker_url;
#endif
        std::vector&lt;std::string&gt; trackers;
        std::vector&lt;std::pair&lt;std::string, int&gt; &gt; dht_nodes;
        sha1_hash info_hash;
        std::string name;
        std::string save_path;
        std::vector&lt;char&gt;* resume_data;
        storage_mode_t storage_mode;
        storage_constructor_type storage;
        void* userdata;
        std::vector&lt;boost::uint8_t&gt; const* file_priorities;
        std::string trackerid;
        std::string url;
        std::string uuid;
        std::string source_feed_url;
        boost::uint64_t flags;
        int max_uploads;
        int max_connections;
        int upload_limit;
        int download_limit;
};

torrent_handle add_torrent(add_torrent_params const&amp; params);
torrent_handle add_torrent(add_torrent_params const&amp; params
        , error_code&amp; ec);
void async_add_torrent(add_torrent_params const&amp; params);
</pre>
</blockquote>
<p>You add torrents through the <tt class="docutils literal">add_torrent()</tt> function where you give an
object with all the parameters. The <tt class="docutils literal">add_torrent()</tt> overloads will block
until the torrent has been added (or failed to be added) and returns an
error code and a <tt class="docutils literal">torrent_handle</tt>. In order to add torrents more efficiently,
consider using <tt class="docutils literal">async_add_torrent()</tt> which returns immediately, without
waiting for the torrent to add. Notification of the torrent being added is sent
as <a class="reference internal" href="#add-torrent-alert">add_torrent_alert</a>.</p>
<p>The overload that does not take an <tt class="docutils literal">error_code</tt> throws an exception on
error and is not available when building without exception support.</p>
<p>The only mandatory parameters are <tt class="docutils literal">save_path</tt> which is the directory where you
want the files to be saved. You also need to specify either the <tt class="docutils literal">ti</tt> (the
torrent file), the <tt class="docutils literal">info_hash</tt> (the info hash of the torrent) or the <tt class="docutils literal">url</tt>
(the URL to where to download the .torrent file from). If you specify the
info-hash, the torrent file will be downloaded from peers, which requires them to
support the metadata extension. For the metadata extension to work, libtorrent must
be built with extensions enabled (<tt class="docutils literal">TORRENT_DISABLE_EXTENSIONS</tt> must not be
defined). It also takes an optional <tt class="docutils literal">name</tt> argument. This may be left empty in case no
name should be assigned to the torrent. In case it's not, the name is used for
the torrent as long as it doesn't have metadata. See <tt class="docutils literal"><span class="pre">torrent_handle::name</span></tt>.</p>
<p>If the torrent doesn't have a tracker, but relies on the DHT to find peers, the
<tt class="docutils literal">trackers</tt> (or the deprecated <tt class="docutils literal">tracker_url</tt>) can specify tracker urls that
for the torrent.</p>
<p>If you specify a <tt class="docutils literal">url</tt>, the torrent will be set in <tt class="docutils literal">downloading_metadata</tt> state
until the .torrent file has been downloaded. If there's any error while downloading,
the torrent will be stopped and the torrent error state (<tt class="docutils literal"><span class="pre">torrent_status::error</span></tt>)
will indicate what went wrong. The <tt class="docutils literal">url</tt> may refer to a magnet link or a regular
http URL.</p>
<p><tt class="docutils literal">dht_nodes</tt> is a list of hostname and port pairs, representing DHT nodes to be
added to the session (if DHT is enabled). The hostname may be an IP address.</p>
<p>If the torrent you are trying to add already exists in the session (is either queued
for checking, being checked or downloading) <tt class="docutils literal">add_torrent()</tt> will throw
<a class="reference internal" href="#libtorrent-exception">libtorrent_exception</a> which derives from <tt class="docutils literal"><span class="pre">std::exception</span></tt> unless <tt class="docutils literal">duplicate_is_error</tt>
is set to false. In that case, <tt class="docutils literal">add_torrent</tt> will return the handle to the existing
torrent.</p>
<p>The optional parameter, <tt class="docutils literal">resume_data</tt> can be given if up to date fast-resume data
is available. The fast-resume data can be acquired from a running torrent by calling
<a class="reference internal" href="#save-resume-data">save_resume_data()</a> on <a class="reference internal" href="#torrent-handle">torrent_handle</a>. See <a class="reference internal" href="#fast-resume">fast resume</a>. The <tt class="docutils literal">vector</tt> that is
passed in will be swapped into the running torrent instance with <tt class="docutils literal"><span class="pre">std::vector::swap()</span></tt>.</p>
<p>The <tt class="docutils literal">storage_mode</tt> parameter refers to the layout of the storage for this torrent.
There are 3 different modes:</p>
<dl class="docutils">
<dt>storage_mode_sparse</dt>
<dd>All pieces will be written to the place where they belong and sparse files
will be used. This is the recommended, and default mode.</dd>
<dt>storage_mode_allocate</dt>
<dd>All pieces will be written to their final position, all files will be
allocated in full when the torrent is first started. This is done with
<tt class="docutils literal">fallocate()</tt> and similar calls. This mode minimizes fragmentation.</dd>
<dt>storage_mode_compact</dt>
<dd><strong>this mode is deprecated and will be removed in future versions of libtorrent</strong>
The storage will grow as more pieces are downloaded, and pieces
are rearranged to finally be in their correct places once the entire torrent has been
downloaded.</dd>
</dl>
<p>For more information, see <a class="reference internal" href="#storage-allocation">storage allocation</a>.</p>
<p><tt class="docutils literal">storage</tt> can be used to customize how the data is stored. The default
storage will simply write the data to the files it belongs to, but it could be
overridden to save everything to a single file at a specific location or encrypt the
content on disk for instance. For more information about the <tt class="docutils literal">storage_interface</tt>
that needs to be implemented for a custom storage, see <a class="reference internal" href="#storage-interface">storage_interface</a>.</p>
<p>The <tt class="docutils literal">userdata</tt> parameter is optional and will be passed on to the extension
constructor functions, if any (see <a class="reference internal" href="#add-extension">add_extension()</a>).</p>
<p>The <a class="reference internal" href="#torrent-handle">torrent_handle</a> returned by <tt class="docutils literal">add_torrent()</tt> can be used to retrieve information
about the torrent's progress, its peers etc. It is also used to abort a torrent.</p>
<p><tt class="docutils literal">file_priorities</tt> can be set to control the initial file priorities when adding
a torrent. The semantics are the same as for <tt class="docutils literal"><span class="pre">torrent_handle::prioritize_files()</span></tt>.</p>
<p><tt class="docutils literal">version</tt> is filled in by the constructor and should be left untouched. It
is used for forward binary compatibility.</p>
<p><tt class="docutils literal">trackerid</tt> is the default tracker id to be used when announcing to trackers. By default
this is empty, and no tracker ID is used, since this is an optional argument. If
a tracker returns a tracker ID, that ID is used instead of this.</p>
<p>if <tt class="docutils literal">uuid</tt> is specified, it is used to find duplicates. If another torrent is already
running with the same UUID as the one being added, it will be considered a duplicate. This
is mainly useful for RSS feed items which has UUIDs specified.</p>
<p><tt class="docutils literal">source_feed_url</tt> should point to the URL of the RSS feed this torrent comes from,
if it comes from an RSS feed.</p>
<p><tt class="docutils literal">flags</tt> is a 64 bit integer used for flags controlling aspects of this torrent
and how it's added. These are the flags:</p>
<pre class="literal-block">
enum flags_t
{
        flag_seed_mode = 0x001,
        flag_override_resume_data = 0x002,
        flag_upload_mode = 0x004,
        flag_share_mode = 0x008,
        flag_apply_ip_filter = 0x010,
        flag_paused = 0x020,
        flag_auto_managed = 0x040.
        flag_duplicate_is_error = 0x080,
        flag_merge_resume_trackers = 0x100,
        flag_update_subscribe = 0x200,
        flag_super_seeding = 0x400,
        flag_sequential_download = 0x800
}
</pre>
<p><tt class="docutils literal">flag_apply_ip_filter</tt> determines if the IP filter should apply to this torrent or not. By
default all torrents are subject to filtering by the IP filter (i.e. this flag is set by
default). This is useful if certain torrents needs to be excempt for some reason, being
an auto-update torrent for instance.</p>
<p><tt class="docutils literal">flag_merge_resume_trackers</tt> defaults to off and specifies whether tracker URLs loaded from
resume data should be added to the trackers in the torrent or replace the trackers.</p>
<p><tt class="docutils literal">flag_update_subscribe</tt> is on by default and means that this torrent will be part of state
updates when calling <a class="reference internal" href="#post-torrent-updates">post_torrent_updates()</a>.</p>
<p><tt class="docutils literal">flag_paused</tt> specifies whether or not the torrent is to be started in a paused
state. I.e. it won't connect to the tracker or any of the peers until it's
resumed. This is typically a good way of avoiding race conditions when setting
configuration options on torrents before starting them.</p>
<p>If you pass in resume data, the paused state of the torrent when the resume data
was saved will override the paused state you pass in here. You can override this
by setting <tt class="docutils literal">flag_override_resume_data</tt>.</p>
<p>If the torrent is auto-managed (<tt class="docutils literal">flag_auto_managed</tt>), the torrent may be resumed
at any point, regardless of how it paused. If it's important to manually control
when the torrent is paused and resumed, don't make it auto managed.</p>
<p>If <tt class="docutils literal">flag_auto_managed</tt> is set, the torrent will be queued, started and seeded
automatically by libtorrent. When this is set, the torrent should also be started
as paused. The default queue order is the order the torrents were added. They
are all downloaded in that order. For more details, see <a class="reference internal" href="#queuing">queuing</a>.</p>
<p>If you pass in resume data, the auto_managed state of the torrent when the resume data
was saved will override the auto_managed state you pass in here. You can override this
by setting <tt class="docutils literal">override_resume_data</tt>.</p>
<p>If <tt class="docutils literal">flag_seed_mode</tt> is set, libtorrent will assume that all files are present
for this torrent and that they all match the hashes in the torrent file. Each time
a peer requests to download a block, the piece is verified against the hash, unless
it has been verified already. If a hash fails, the torrent will automatically leave
the seed mode and recheck all the files. The use case for this mode is if a torrent
is created and seeded, or if the user already know that the files are complete, this
is a way to avoid the initial file checks, and significantly reduce the startup time.</p>
<p>Setting <tt class="docutils literal">flag_seed_mode</tt> on a torrent without metadata (a .torrent file) is a no-op
and will be ignored.</p>
<p>If resume data is passed in with this torrent, the seed mode saved in there will
override the seed mode you set here.</p>
<p>If <tt class="docutils literal">flag_override_resume_data</tt> is set, the <tt class="docutils literal">paused</tt> and <tt class="docutils literal">auto_managed</tt>
state of the torrent are not loaded from the resume data, but the states requested
by the flags in <tt class="docutils literal">add_torrent_params</tt> will override them.</p>
<p>If <tt class="docutils literal">flag_upload_mode</tt> is set, the torrent will be initialized in upload-mode,
which means it will not make any piece requests. This state is typically entered
on disk I/O errors, and if the torrent is also auto managed, it will be taken out
of this state periodically. This mode can be used to avoid race conditions when
adjusting priorities of pieces before allowing the torrent to start downloading.</p>
<p>If the torrent is auto-managed (<tt class="docutils literal">flag_auto_managed</tt>), the torrent will eventually
be taken out of upload-mode, regardless of how it got there. If it's important to
manually control when the torrent leaves upload mode, don't make it auto managed.</p>
<p><tt class="docutils literal">flag_share_mode</tt> determines if the torrent should be added in <em>share mode</em> or not.
Share mode indicates that we are not interested in downloading the torrent, but
merlely want to improve our share ratio (i.e. increase it). A torrent started in
share mode will do its best to never download more than it uploads to the swarm.
If the swarm does not have enough demand for upload capacity, the torrent will
not download anything. This mode is intended to be safe to add any number of torrents
to, without manual screening, without the risk of downloading more than is uploaded.</p>
<p>A torrent in share mode sets the priority to all pieces to 0, except for the pieces
that are downloaded, when pieces are decided to be downloaded. This affects the progress
bar, which might be set to &quot;100% finished&quot; most of the time. Do not change file or piece
priorities for torrents in share mode, it will make it not work.</p>
<p>The share mode has one setting, the share ratio target, see <tt class="docutils literal"><span class="pre">session_settings::share_mode_target</span></tt>
for more info.</p>
<p><tt class="docutils literal">flag_super_seeding</tt> sets the torrent into super seeding mode. If the torrent
is not a seed, this flag has no effect. It has the same effect as calling
<tt class="docutils literal"><span class="pre">torrent_handle::super_seeding(true)</span></tt> on the torrent handle immediately
after adding it.</p>
<p><tt class="docutils literal">flag_sequential_download</tt> sets the sequential download state for the torrent.
It has the same effect as calling <tt class="docutils literal"><span class="pre">torrent_handle::sequential_download(true)</span></tt>
on the torrent handle immediately after adding it.</p>
<p><tt class="docutils literal">max_uploads</tt>, <tt class="docutils literal">max_connections</tt>, <tt class="docutils literal">upload_limit</tt>, <tt class="docutils literal">download_limit</tt> correspond
to the <tt class="docutils literal">set_max_uploads()</tt>, <tt class="docutils literal">set_max_connections()</tt>, <tt class="docutils literal">set_upload_limit()</tt> and
<tt class="docutils literal">set_download_limit()</tt> functions on <a class="reference internal" href="#torrent-handle">torrent_handle</a>. These values let you initialize
these settings when the torrent is added, instead of calling these functions immediately
following adding it.</p>
</div>
<div class="section" id="remove-torrent">
<h2>remove_torrent()</h2>
<blockquote>
<pre class="literal-block">
void remove_torrent(torrent_handle const&amp; h, int options = none);
</pre>
</blockquote>
<p><tt class="docutils literal">remove_torrent()</tt> will close all peer connections associated with the torrent and tell
the tracker that we've stopped participating in the swarm. The optional second argument
<tt class="docutils literal">options</tt> can be used to delete all the files downloaded by this torrent. To do this, pass
in the value <tt class="docutils literal"><span class="pre">session::delete_files</span></tt>. The removal of the torrent is asyncronous, there is
no guarantee that adding the same torrent immediately after it was removed will not throw
a <a class="reference internal" href="#libtorrent-exception">libtorrent_exception</a> exception. Once the torrent is deleted, a <a class="reference internal" href="#torrent-deleted-alert">torrent_deleted_alert</a>
is posted.</p>
</div>
<div class="section" id="find-torrent-get-torrents">
<h2>find_torrent() get_torrents()</h2>
<blockquote>
<pre class="literal-block">
torrent_handle find_torrent(sha_hash const&amp; ih);
std::vector&lt;torrent_handle&gt; get_torrents() const;
</pre>
</blockquote>
<p><tt class="docutils literal">find_torrent()</tt> looks for a torrent with the given info-hash. In case there
is such a torrent in the session, a torrent_handle to that torrent is returned.
In case the torrent cannot be found, an invalid torrent_handle is returned.</p>
<p>See <tt class="docutils literal"><span class="pre">torrent_handle::is_valid()</span></tt> to know if the torrent was found or not.</p>
<p><tt class="docutils literal">get_torrents()</tt> returns a vector of torrent_handles to all the torrents
currently in the session.</p>
</div>
<div class="section" id="get-torrent-status-refresh-torrent-status">
<h2>get_torrent_status() refresh_torrent_status()</h2>
<blockquote>
<pre class="literal-block">
void get_torrent_status(std::vector&lt;torrent_status&gt;* ret
        , boost::function&lt;bool(torrent_status const&amp;)&gt; const&amp; pred
        , boost::uint32_t flags = 0) const;
void refresh_torrent_status(std::vector&lt;torrent_status&gt;* ret
        , boost::uint32_t flags = 0) const;
</pre>
</blockquote>
<div class="note">
<p class="first admonition-title">Note</p>
<p class="last">these calls are potentially expensive and won't scale well
with lots of torrents. If you're concerned about performance, consider
using <tt class="docutils literal">post_torrent_updates()</tt> instead.</p>
</div>
<p><tt class="docutils literal">get_torrent_status</tt> returns a vector of the <tt class="docutils literal">torrent_status</tt> for every
torrent which satisfies <tt class="docutils literal">pred</tt>, which is a predicate function which determines
if a torrent should be included in the returned set or not. Returning true means
it should be included and false means excluded. The <tt class="docutils literal">flags</tt> argument is the same
as to <tt class="docutils literal"><span class="pre">torrent_handle::status()</span></tt>. Since <tt class="docutils literal">pred</tt> is guaranteed to be called for
every torrent, it may be used to count the number of torrents of different categories
as well.</p>
<p><tt class="docutils literal">refresh_torrent_status</tt> takes a vector of <tt class="docutils literal">torrent_status</tt> structs (for instance
the same vector that was returned by <tt class="docutils literal">get_torrent_status()</tt>) and refreshes the
status based on the <tt class="docutils literal">handle</tt> member. It is possible to use this function by
first setting up a vector of default constructed <tt class="docutils literal">torrent_status</tt> objects, only
initializing the <tt class="docutils literal">handle</tt> member, in order to request the torrent status for
multiple torrents in a single call. This can save a significant amount of time
if you have a lot of torrents.</p>
<p>Any <tt class="docutils literal">torrent_status</tt> object whose <tt class="docutils literal">handle</tt> member is not referring to a
valid torrent are ignored.</p>
</div>
<div class="section" id="post-torrent-updates">
<h2>post_torrent_updates()</h2>
<blockquote>
<pre class="literal-block">
void post_torrent_updates();
</pre>
</blockquote>
<p>This functions instructs the session to post the <a class="reference internal" href="#state-update-alert">state_update_alert</a>, containing
the status of all torrents whose state changed since the last time this function
was called.</p>
<p>Only torrents who has the state subscription flag set will be included. This flag
is on by default. See <tt class="docutils literal">add_torrent_params</tt> under <a class="reference internal" href="#async-add-torrent-add-torrent">async_add_torrent() add_torrent()</a>.</p>
</div>
<div class="section" id="load-asnum-db-load-country-db-as-for-ip">
<h2>load_asnum_db() load_country_db() as_for_ip()</h2>
<blockquote>
<pre class="literal-block">
void load_asnum_db(char const* file);
void load_asnum_db(wchar_t const* file);
void load_country_db(char const* file);
void load_country_db(wchar_t const* file);
int as_for_ip(address const&amp; adr);
</pre>
</blockquote>
<p>These functions are not available if <tt class="docutils literal">TORRENT_DISABLE_GEO_IP</tt> is defined. They
expects a path to the <a class="reference external" href="http://www.maxmind.com/app/asnum">MaxMind ASN database</a> and <a class="reference external" href="http://www.maxmind.com/app/geolitecountry">MaxMind GeoIP database</a>
respectively. This will be used to look up which AS and country peers belong to.</p>
<p><tt class="docutils literal">as_for_ip</tt> returns the AS number for the IP address specified. If the IP is not
in the database or the ASN database is not loaded, 0 is returned.</p>
<p>The <tt class="docutils literal">wchar_t</tt> overloads are for wide character paths.</p>
</div>
<div class="section" id="set-ip-filter">
<h2>set_ip_filter()</h2>
<blockquote>
<pre class="literal-block">
void set_ip_filter(ip_filter const&amp; filter);
</pre>
</blockquote>
<p>Sets a filter that will be used to reject and accept incoming as well as outgoing
connections based on their originating ip address. The default filter will allow
connections to any ip address. To build a set of rules for which addresses are
accepted and not, see <a class="reference internal" href="#ip-filter">ip_filter</a>.</p>
<p>Each time a peer is blocked because of the IP filter, a <a class="reference internal" href="#peer-blocked-alert">peer_blocked_alert</a> is
generated.</p>
</div>
<div class="section" id="get-ip-filter">
<h2>get_ip_filter()</h2>
<blockquote>
<pre class="literal-block">
ip_filter get_ip_filter() const;
</pre>
</blockquote>
<p>Returns the ip_filter currently in the session. See <a class="reference internal" href="#ip-filter">ip_filter</a>.</p>
</div>
<div class="section" id="status">
<h2>status()</h2>
<blockquote>
<pre class="literal-block">
session_status status() const;
</pre>
</blockquote>
<p><tt class="docutils literal">status()</tt> returns session wide-statistics and status. The <tt class="docutils literal">session_status</tt>
struct has the following members:</p>
<pre class="literal-block">
struct dht_lookup
{
        char const* type;
        int outstanding_requests;
        int timeouts;
        int responses;
        int branch_factor;
        int nodes_left;
        int last_sent;
        int first_timeout;
};

struct dht_routing_bucket
{
        int num_nodes;
        int num_replacements;
        int last_active;
};

struct utp_status
{
        int num_idle;
        int num_syn_sent;
        int num_connected;
        int num_fin_sent;
        int num_close_wait;
};

struct session_status
{
        bool has_incoming_connections;

        int upload_rate;
        int download_rate;
        size_type total_download;
        size_type total_upload;

        int payload_upload_rate;
        int payload_download_rate;
        size_type total_payload_download;
        size_type total_payload_upload;

        int ip_overhead_upload_rate;
        int ip_overhead_download_rate;
        size_type total_ip_overhead_download;
        size_type total_ip_overhead_upload;

        int dht_upload_rate;
        int dht_download_rate;
        size_type total_dht_download;
        size_type total_dht_upload;

        int tracker_upload_rate;
        int tracker_download_rate;
        size_type total_tracker_download;
        size_type total_tracker_upload;

        size_type total_redundant_bytes;
        size_type total_failed_bytes;

        int num_peers;
        int num_unchoked;
        int allowed_upload_slots;

        int up_bandwidth_queue;
        int down_bandwidth_queue;

        int up_bandwidth_bytes_queue;
        int down_bandwidth_bytes_queue;

        int optimistic_unchoke_counter;
        int unchoke_counter;

        int disk_write_queue;
        int disk_read_queue;

        int dht_nodes;
        int dht_node_cache;
        int dht_torrents;
        size_type dht_global_nodes;
        std::vector&lt;dht_lookup&gt; active_requests;
        std::vector&lt;dht_routing_table&gt; dht_routing_table;
        int dht_total_allocations;

        utp_status utp_stats;
};
</pre>
<p><tt class="docutils literal">has_incoming_connections</tt> is false as long as no incoming connections have been
established on the listening socket. Every time you change the listen port, this will
be reset to false.</p>
<p><tt class="docutils literal">upload_rate</tt>, <tt class="docutils literal">download_rate</tt> are the total download and upload rates accumulated
from all torrents. This includes bittorrent protocol, DHT and an estimated TCP/IP
protocol overhead.</p>
<p><tt class="docutils literal">total_download</tt> and <tt class="docutils literal">total_upload</tt> are the total number of bytes downloaded and
uploaded to and from all torrents. This also includes all the protocol overhead.</p>
<p><tt class="docutils literal">payload_download_rate</tt> and <tt class="docutils literal">payload_upload_rate</tt> is the rate of the payload
down- and upload only.</p>
<p><tt class="docutils literal">total_payload_download</tt> and <tt class="docutils literal">total_payload_upload</tt> is the total transfers of payload
only. The payload does not include the bittorrent protocol overhead, but only parts of the
actual files to be downloaded.</p>
<p><tt class="docutils literal">ip_overhead_upload_rate</tt>, <tt class="docutils literal">ip_overhead_download_rate</tt>, <tt class="docutils literal">total_ip_overhead_download</tt>
and <tt class="docutils literal">total_ip_overhead_upload</tt> is the estimated TCP/IP overhead in each direction.</p>
<p><tt class="docutils literal">dht_upload_rate</tt>, <tt class="docutils literal">dht_download_rate</tt>, <tt class="docutils literal">total_dht_download</tt> and <tt class="docutils literal">total_dht_upload</tt>
is the DHT bandwidth usage.</p>
<p><tt class="docutils literal">total_redundant_bytes</tt> is the number of bytes that has been received more than once.
This can happen if a request from a peer times out and is requested from a different
peer, and then received again from the first one. To make this lower, increase the
<tt class="docutils literal">request_timeout</tt> and the <tt class="docutils literal">piece_timeout</tt> in the session settings.</p>
<p><tt class="docutils literal">total_failed_bytes</tt> is the number of bytes that was downloaded which later failed
the hash-check.</p>
<p><tt class="docutils literal">num_peers</tt> is the total number of peer connections this session has. This includes
incoming connections that still hasn't sent their handshake or outgoing connections
that still hasn't completed the TCP connection. This number may be slightly higher
than the sum of all peers of all torrents because the incoming connections may not
be assigned a torrent yet.</p>
<p><tt class="docutils literal">num_unchoked</tt> is the current number of unchoked peers.
<tt class="docutils literal">allowed_upload_slots</tt> is the current allowed number of unchoked peers.</p>
<p><tt class="docutils literal">up_bandwidth_queue</tt> and <tt class="docutils literal">down_bandwidth_queue</tt> are the number of peers that are
waiting for more bandwidth quota from the torrent rate limiter.
<tt class="docutils literal">up_bandwidth_bytes_queue</tt> and <tt class="docutils literal">down_bandwidth_bytes_queue</tt> count the number of
bytes the connections are waiting for to be able to send and receive.</p>
<p><tt class="docutils literal">optimistic_unchoke_counter</tt> and <tt class="docutils literal">unchoke_counter</tt> tells the number of
seconds until the next optimistic unchoke change and the start of the next
unchoke interval. These numbers may be reset prematurely if a peer that is
unchoked disconnects or becomes notinterested.</p>
<p><tt class="docutils literal">disk_write_queue</tt> and <tt class="docutils literal">disk_read_queue</tt> are the number of peers currently
waiting on a disk write or disk read to complete before it receives or sends
any more data on the socket. It'a a metric of how disk bound you are.</p>
<p><tt class="docutils literal">dht_nodes</tt>, <tt class="docutils literal">dht_node_cache</tt> and <tt class="docutils literal">dht_torrents</tt> are only available when
built with DHT support. They are all set to 0 if the DHT isn't running. When
the DHT is running, <tt class="docutils literal">dht_nodes</tt> is set to the number of nodes in the routing
table. This number only includes <em>active</em> nodes, not cache nodes. The
<tt class="docutils literal">dht_node_cache</tt> is set to the number of nodes in the node cache. These nodes
are used to replace the regular nodes in the routing table in case any of them
becomes unresponsive.</p>
<p><tt class="docutils literal">dht_torrents</tt> are the number of torrents tracked by the DHT at the moment.</p>
<p><tt class="docutils literal">dht_global_nodes</tt> is an estimation of the total number of nodes in the DHT
network.</p>
<p><tt class="docutils literal">active_requests</tt> is a vector of the currently running DHT lookups.</p>
<p><tt class="docutils literal">dht_routing_table</tt> contains information about every bucket in the DHT routing
table.</p>
<p><tt class="docutils literal">dht_total_allocations</tt> is the number of nodes allocated dynamically for a
particular DHT lookup. This represents roughly the amount of memory used
by the DHT.</p>
<p><tt class="docutils literal">utp_stats</tt> contains statistics on the uTP sockets.</p>
</div>
<div class="section" id="get-cache-status">
<h2>get_cache_status()</h2>
<blockquote>
<pre class="literal-block">
cache_status get_cache_status() const;
</pre>
</blockquote>
<p>Returns status of the disk cache for this session.</p>
<blockquote>
<pre class="literal-block">
struct cache_status
{
        size_type blocks_written;
        size_type writes;
        size_type blocks_read;
        size_type blocks_read_hit;
        size_type reads;
        int cache_size;
        int read_cache_size;
        int total_used_buffers;
        int average_queue_time;
        int average_read_time;
        int average_write_time;
        int average_hash_time;
        int average_cache_time;
        int job_queue_length;
};
</pre>
</blockquote>
<p><tt class="docutils literal">blocks_written</tt> is the total number of 16 KiB blocks written to disk
since this session was started.</p>
<p><tt class="docutils literal">writes</tt> is the total number of write operations performed since this
session was started.</p>
<p>The ratio (<tt class="docutils literal">blocks_written</tt> - <tt class="docutils literal">writes</tt>) / <tt class="docutils literal">blocks_written</tt> represents
the number of saved write operations per total write operations. i.e. a kind
of cache hit ratio for the write cahe.</p>
<p><tt class="docutils literal">blocks_read</tt> is the number of blocks that were requested from the
bittorrent engine (from peers), that were served from disk or cache.</p>
<p><tt class="docutils literal">blocks_read_hit</tt> is the number of blocks that were served from cache.</p>
<p>The ratio <tt class="docutils literal">blocks_read_hit</tt> / <tt class="docutils literal">blocks_read</tt> is the cache hit ratio
for the read cache.</p>
<p><tt class="docutils literal">cache_size</tt> is the number of 16 KiB blocks currently in the disk cache.
This includes both read and write cache.</p>
<p><tt class="docutils literal">read_cache_size</tt> is the number of 16KiB blocks in the read cache.</p>
<p><tt class="docutils literal">total_used_buffers</tt> is the total number of buffers currently in use.
This includes the read/write disk cache as well as send and receive buffers
used in peer connections.</p>
<p><tt class="docutils literal">average_queue_time</tt> is the number of microseconds an average disk I/O job
has to wait in the job queue before it get processed.</p>
<p><tt class="docutils literal">average_read_time</tt> is the time read jobs takes on average to complete
(not including the time in the queue), in microseconds. This only measures
read cache misses.</p>
<p><tt class="docutils literal">average_write_time</tt> is the time write jobs takes to complete, on average,
in microseconds. This does not include the time the job sits in the disk job
queue or in the write cache, only blocks that are flushed to disk.</p>
<p><tt class="docutils literal">average_hash_time</tt> is the time hash jobs takes to complete on average, in
microseconds. Hash jobs include running SHA-1 on the data (which for the most
part is done incrementally) and sometimes reading back parts of the piece. It
also includes checking files without valid resume data.</p>
<p><tt class="docutils literal">average_cache_time</tt> is the average amuount of time spent evicting cached
blocks that have expired from the disk cache.</p>
<p><tt class="docutils literal">job_queue_length</tt> is the number of jobs in the job queue.</p>
</div>
<div class="section" id="get-cache-info">
<h2>get_cache_info()</h2>
<blockquote>
<pre class="literal-block">
void get_cache_info(sha1_hash const&amp; ih
        , std::vector&lt;cached_piece_info&gt;&amp; ret) const;
</pre>
</blockquote>
<p><tt class="docutils literal">get_cache_info()</tt> fills out the supplied vector with information for
each piece that is currently in the disk cache for the torrent with the
specified info-hash (<tt class="docutils literal">ih</tt>).</p>
<blockquote>
<pre class="literal-block">
struct cached_piece_info
{
        int piece;
        std::vector&lt;bool&gt; blocks;
        ptime last_use;
        enum kind_t { read_cache = 0, write_cache = 1 };
        kind_t kind;
};
</pre>
</blockquote>
<p><tt class="docutils literal">piece</tt> is the piece index for this cache entry.</p>
<p><tt class="docutils literal">blocks</tt> has one entry for each block in this piece. <tt class="docutils literal">true</tt> represents
the data for that block being in the disk cache and <tt class="docutils literal">false</tt> means it's not.</p>
<p><tt class="docutils literal">last_use</tt> is the time when a block was last written to this piece. The older
a piece is, the more likely it is to be flushed to disk.</p>
<p><tt class="docutils literal">kind</tt> specifies if this piece is part of the read cache or the write cache.</p>
</div>
<div class="section" id="is-listening-listen-port-listen-on">
<h2>is_listening() listen_port() listen_on()</h2>
<blockquote>
<pre class="literal-block">
bool is_listening() const;
unsigned short listen_port() const;

enum {
        listen_reuse_address = 1,
        listen_no_system_port = 2
};

void listen_on(
        std::pair&lt;int, int&gt; const&amp; port_range
        , error_code&amp; ec
        , char const* interface = 0
        , int flags = 0);
</pre>
</blockquote>
<p><tt class="docutils literal">is_listening()</tt> will tell you whether or not the session has successfully
opened a listening port. If it hasn't, this function will return false, and
then you can use <tt class="docutils literal">listen_on()</tt> to make another attempt.</p>
<p><tt class="docutils literal">listen_port()</tt> returns the port we ended up listening on. Since you just pass
a port-range to the constructor and to <tt class="docutils literal">listen_on()</tt>, to know which port it
ended up using, you have to ask the session using this function.</p>
<p><tt class="docutils literal">listen_on()</tt> will change the listen port and/or the listen interface. If the
session is already listening on a port, this socket will be closed and a new socket
will be opened with these new settings. The port range is the ports it will try
to listen on, if the first port fails, it will continue trying the next port within
the range and so on. The interface parameter can be left as 0, in that case the
os will decide which interface to listen on, otherwise it should be the ip-address
of the interface you want the listener socket bound to. <tt class="docutils literal">listen_on()</tt> returns the
error code of the operation in <tt class="docutils literal">ec</tt>. If this indicates success, the session is
listening on a port within the specified range. If it fails, it will also
generate an appropriate alert (<a class="reference internal" href="#listen-failed-alert">listen_failed_alert</a>).</p>
<p>If all ports in the specified range fails to be opened for listening, libtorrent will
try to use port 0 (which tells the operating system to pick a port that's free). If
that still fails you may see a <a class="reference internal" href="#listen-failed-alert">listen_failed_alert</a> with port 0 even if you didn't
ask to listen on it.</p>
<p>It is possible to prevent libtorrent from binding to port 0 by passing in the flag
<tt class="docutils literal"><span class="pre">session::no_system_port</span></tt> in the <tt class="docutils literal">flags</tt> argument.</p>
<p>The interface parameter can also be a hostname that will resolve to the device you
want to listen on. If you don't specify an interface, libtorrent may attempt to
listen on multiple interfaces (typically 0.0.0.0 and ::). This means that if your
IPv6 interface doesn't work, you may still see a <a class="reference internal" href="#listen-failed-alert">listen_failed_alert</a>, even though
the IPv4 port succeeded.</p>
<p>The <tt class="docutils literal">flags</tt> parameter can either be 0 or <tt class="docutils literal"><span class="pre">session::listen_reuse_address</span></tt>, which
will set the reuse address socket option on the listen socket(s). By default, the
listen socket does not use reuse address. If you're running a service that needs
to run on a specific port no matter if it's in use, set this flag.</p>
<p>If you're also starting the DHT, it is a good idea to do that after you've called
<tt class="docutils literal">listen_on()</tt>, since the default listen port for the DHT is the same as the tcp
listen socket. If you start the DHT first, it will assume the tcp port is free and
open the udp socket on that port, then later, when <tt class="docutils literal">listen_on()</tt> is called, it
may turn out that the tcp port is in use. That results in the DHT and the bittorrent
socket listening on different ports. If the DHT is active when <tt class="docutils literal">listen_on</tt> is
called, the udp port will be rebound to the new port, if it was configured to use
the same port as the tcp socket, and if the listen_on call failed to bind to the
same port that the udp uses.</p>
<p>If you want the OS to pick a port for you, pass in 0 as both first and second.</p>
<p>The reason why it's a good idea to run the DHT and the bittorrent socket on the same
port is because that is an assumption that may be used to increase performance. One
way to accelerate the connecting of peers on windows may be to first ping all peers
with a DHT ping packet, and connect to those that responds first. On windows one
can only connect to a few peers at a time because of a built in limitation (in XP
Service pack 2).</p>
</div>
<div class="section" id="set-alert-mask">
<h2>set_alert_mask()</h2>
<blockquote>
<pre class="literal-block">
void set_alert_mask(int m);
</pre>
</blockquote>
<p>Changes the mask of which alerts to receive. By default only errors are reported.
<tt class="docutils literal">m</tt> is a bitmask where each bit represents a category of alerts.</p>
<p>See <a class="reference internal" href="#alerts">alerts</a> for mor information on the alert categories.</p>
</div>
<div class="section" id="pop-alerts-pop-alert-wait-for-alert">
<h2>pop_alerts() pop_alert() wait_for_alert()</h2>
<blockquote>
<pre class="literal-block">
std::auto_ptr&lt;alert&gt; pop_alert();
void pop_alerts(std::deque&lt;alert*&gt;* alerts);
alert const* wait_for_alert(time_duration max_wait);
</pre>
</blockquote>
<p><tt class="docutils literal">pop_alert()</tt> is used to ask the session if any errors or events has occurred. With
<a class="reference internal" href="#set-alert-mask">set_alert_mask()</a> you can filter which alerts to receive through <tt class="docutils literal">pop_alert()</tt>.
For information about the alert categories, see <a class="reference internal" href="#alerts">alerts</a>.</p>
<p><tt class="docutils literal">pop_alerts()</tt> pops all pending alerts in a single call. In high performance environments
with a very high alert churn rate, this can save significant amount of time compared to
popping alerts one at a time. Each call requires one round-trip to the network thread. If
alerts are produced in a higher rate than they can be popped (when popped one at a time)
it's easy to get stuck in an infinite loop, trying to drain the alert queue. Popping the entire
queue at once avoids this problem.</p>
<p>However, the <tt class="docutils literal">pop_alerts</tt> function comes with significantly more responsibility. You pass
in an <em>empty</em> <tt class="docutils literal"><span class="pre">std::dequeue&lt;alert*&gt;</span></tt> to it. If it's not empty, all elements in it will
be deleted and then cleared. All currently pending alerts are returned by being swapped
into the passed in container. The responsibility of deleting the alerts is transferred
to the caller. This means you need to call delete for each item in the returned dequeue.
It's probably a good idea to delete the alerts as you handle them, to save one extra
pass over the dequeue.</p>
<p>Alternatively, you can pass in the same container the next time you call <tt class="docutils literal">pop_alerts</tt>.</p>
<p><tt class="docutils literal">wait_for_alert</tt> blocks until an alert is available, or for no more than <tt class="docutils literal">max_wait</tt>
time. If <tt class="docutils literal">wait_for_alert</tt> returns because of the time-out, and no alerts are available,
it returns 0. If at least one alert was generated, a pointer to that alert is returned.
The alert is not popped, any subsequent calls to <tt class="docutils literal">wait_for_alert</tt> will return the
same pointer until the alert is popped by calling <tt class="docutils literal">pop_alert</tt>. This is useful for
leaving any alert dispatching mechanism independent of this blocking call, the dispatcher
can be called and it can pop the alert independently.</p>
<p>In the python binding, <tt class="docutils literal">wait_for_alert</tt> takes the number of milliseconds to wait as an integer.</p>
<p>To control the max number of alerts that's queued by the session, see
<tt class="docutils literal"><span class="pre">session_settings::alert_queue_size</span></tt>.</p>
<p><tt class="docutils literal">save_resume_data_alert</tt> and <tt class="docutils literal">save_resume_data_failed_alert</tt> are always posted, regardelss
of the alert mask.</p>
</div>
<div class="section" id="set-alert-dispatch">
<h2>set_alert_dispatch()</h2>
<blockquote>
<pre class="literal-block">
void set_alert_dispatch(boost::function&lt;void(std::auto_ptr&lt;alert&gt;)&gt; const&amp; fun);
</pre>
</blockquote>
<p>This sets a function to be called (from within libtorrent's netowrk thread) every time an alert
is posted. Since the function (<tt class="docutils literal">fun</tt>) is run in libtorrent's internal thread, it may not call
any of libtorrent's external API functions. Doing so results in a dead lock.</p>
<p>The main intention with this function is to support integration with platform-dependent message
queues or signalling systems. For instance, on windows, one could post a message to an HNWD or
on linux, write to a pipe or an eventfd.</p>
</div>
<div class="section" id="add-feed">
<h2>add_feed()</h2>
<blockquote>
<pre class="literal-block">
feed_handle session::add_feed(feed_settings const&amp; feed);
</pre>
</blockquote>
<p>This adds an RSS feed to the session. The feed will be refreshed
regularly and optionally add all torrents from the feed, as they
appear. The feed is defined by the <tt class="docutils literal">feed_settings</tt> object:</p>
<pre class="literal-block">
struct feed_settings
{
        feed_settings();

std::string url;
        bool auto_download;
        bool auto_map_handles;
        int default_ttl;
        add_torrent_params add_args;
};
</pre>
<p>By default <tt class="docutils literal">auto_download</tt> is true, which means all torrents in
the feed will be downloaded. Set this to false in order to manually
add torrents to the session. You may react to the <a class="reference internal" href="#rss-alert">rss_alert</a> when
a feed has been updated to poll it for the new items in the feed
when adding torrents manually. When torrents are added automatically,
an <a class="reference internal" href="#add-torrent-alert">add_torrent_alert</a> is posted which includes the torrent handle
as well as the error code if it failed to be added. You may also call
<tt class="docutils literal"><span class="pre">session::get_torrents()</span></tt> to get the handles to the new torrents.</p>
<p>Before adding the feed, you must set the <tt class="docutils literal">url</tt> field to the
feed's url. It may point to an RSS or an atom feed.</p>
<p><tt class="docutils literal">auto_map_handles</tt> defaults to true and determines whether or
not to set the <tt class="docutils literal">handle</tt> field in the <tt class="docutils literal">feed_item</tt>, returned
as the feed status. If auto-download is enabled, this setting
is ignored. If auto-download is not set, setting this to false
will save one pass through all the feed items trying to find
corresponding torrents in the session.</p>
<p>The <tt class="docutils literal">default_ttl</tt> is the default interval for refreshing a feed.
This may be overridden by the feed itself (by specifying the <tt class="docutils literal">&lt;ttl&gt;</tt>
tag) and defaults to 30 minutes. The field specifies the number of
minutes between refreshes.</p>
<p>If torrents are added automatically, you may want to set the
<tt class="docutils literal">add_args</tt> to appropriate values for download directory etc.
This object is used as a template for adding torrents from feeds,
but some torrent specific fields will be overridden by the
individual torrent being added. For more information on the
<tt class="docutils literal">add_torrent_params</tt>, see <a class="reference internal" href="#async-add-torrent-add-torrent">async_add_torrent() add_torrent()</a>.</p>
<p>The returned <a class="reference internal" href="#feed-handle">feed_handle</a> is a handle which is used to interact
with the feed, things like forcing a refresh or querying for
information about the items in the feed. For more information,
see <a class="reference internal" href="#feed-handle">feed_handle</a>.</p>
</div>
<div class="section" id="remove-feed">
<h2>remove_feed()</h2>
<blockquote>
<pre class="literal-block">
void session::remove_feed(feed_handle h);
</pre>
</blockquote>
<p>Removes a feed from being watched by the session. When this
call returns, the feed handle is invalid and won't refer
to any feed.</p>
</div>
<div class="section" id="get-feeds">
<h2>get_feeds()</h2>
<blockquote>
<pre class="literal-block">
void session::get_feeds(std::vector&lt;feed_handle&gt;&amp; f) const;
</pre>
</blockquote>
<p>Returns a list of all RSS feeds that are being watched by the session.</p>
</div>
<div class="section" id="add-extension">
<h2>add_extension()</h2>
<blockquote>
<pre class="literal-block">
void add_extension(boost::function&lt;
        boost::shared_ptr&lt;torrent_plugin&gt;(torrent*, void*)&gt; ext);
</pre>
</blockquote>
<p>This function adds an extension to this session. The argument is a function
object that is called with a <tt class="docutils literal">torrent*</tt> and which should return a
<tt class="docutils literal"><span class="pre">boost::shared_ptr&lt;torrent_plugin&gt;</span></tt>. To write custom plugins, see
<a class="reference external" href="libtorrent_plugins.html">libtorrent plugins</a>. For the typical bittorrent client all of these
extensions should be added. The main plugins implemented in libtorrent are:</p>
<dl class="docutils">
<dt>metadata extension</dt>
<dd>Allows peers to download the metadata (.torren files) from the swarm
directly. Makes it possible to join a swarm with just a tracker and
info-hash.</dd>
</dl>
<pre class="literal-block">
#include &lt;libtorrent/extensions/metadata_transfer.hpp&gt;
ses.add_extension(&amp;libtorrent::create_metadata_plugin);
</pre>
<dl class="docutils">
<dt>uTorrent metadata</dt>
<dd>Same as <tt class="docutils literal">metadata extension</tt> but compatible with uTorrent.</dd>
</dl>
<pre class="literal-block">
#include &lt;libtorrent/extensions/ut_metadata.hpp&gt;
ses.add_extension(&amp;libtorrent::create_ut_metadata_plugin);
</pre>
<dl class="docutils">
<dt>uTorrent peer exchange</dt>
<dd>Exchanges peers between clients.</dd>
</dl>
<pre class="literal-block">
#include &lt;libtorrent/extensions/ut_pex.hpp&gt;
ses.add_extension(&amp;libtorrent::create_ut_pex_plugin);
</pre>
<dl class="docutils">
<dt>smart ban plugin</dt>
<dd>A plugin that, with a small overhead, can ban peers
that sends bad data with very high accuracy. Should
eliminate most problems on poisoned torrents.</dd>
</dl>
<pre class="literal-block">
#include &lt;libtorrent/extensions/smart_ban.hpp&gt;
ses.add_extension(&amp;libtorrent::create_smart_ban_plugin);
</pre>
</div>
<div class="section" id="set-settings-set-pe-settings">
<h2>set_settings() set_pe_settings()</h2>
<blockquote>
<pre class="literal-block">
void set_settings(session_settings const&amp; settings);
void set_pe_settings(pe_settings const&amp; settings);
</pre>
</blockquote>
<p>Sets the session settings and the packet encryption settings respectively.
See <a class="reference internal" href="#session-settings">session_settings</a> and <a class="reference internal" href="#pe-settings">pe_settings</a> for more information on available
options.</p>
</div>
<div class="section" id="set-proxy-proxy">
<h2>set_proxy() proxy()</h2>
<blockquote>
<pre class="literal-block">
void set_proxy(proxy_settings const&amp; s);
proxy_setting proxy() const;
</pre>
</blockquote>
<p>These functions sets and queries the proxy settings to be used for the session.</p>
<p>For more information on what settings are available for proxies, see
<a class="reference internal" href="#proxy-settings">proxy_settings</a>.</p>
</div>
<div class="section" id="set-i2p-proxy-i2p-proxy">
<h2>set_i2p_proxy() i2p_proxy()</h2>
<blockquote>
<pre class="literal-block">
void set_i2p_proxy(proxy_settings const&amp;);
proxy_settings const&amp; i2p_proxy();
</pre>
</blockquote>
<p><tt class="docutils literal">set_i2p_proxy</tt> sets the <a class="reference external" href="http://www.i2p2.de">i2p</a> proxy, and tries to open a persistant
connection to it. The only used fields in the proxy settings structs
are <tt class="docutils literal">hostname</tt> and <tt class="docutils literal">port</tt>.</p>
<p><tt class="docutils literal">i2p_proxy</tt> returns the current i2p proxy in use.</p>
</div>
<div class="section" id="start-dht-stop-dht-set-dht-settings-dht-state-is-dht-running">
<h2>start_dht() stop_dht() set_dht_settings() dht_state() is_dht_running()</h2>
<blockquote>
<pre class="literal-block">
void start_dht(entry const&amp; startup_state);
void stop_dht();
void set_dht_settings(dht_settings const&amp; settings);
entry dht_state() const;
bool is_dht_running() const;
</pre>
</blockquote>
<p>These functions are not available in case <tt class="docutils literal">TORRENT_DISABLE_DHT</tt> is
defined. <tt class="docutils literal">start_dht</tt> starts the dht node and makes the trackerless service
available to torrents. The startup state is optional and can contain nodes
and the node id from the previous session. The dht node state is a bencoded
dictionary with the following entries:</p>
<dl class="docutils">
<dt><tt class="docutils literal">nodes</tt></dt>
<dd>A list of strings, where each string is a node endpoint encoded in binary. If
the string is 6 bytes long, it is an IPv4 address of 4 bytes, encoded in
network byte order (big endian), followed by a 2 byte port number (also
network byte order). If the string is 18 bytes long, it is 16 bytes of IPv6
address followed by a 2 bytes port number (also network byte order).</dd>
<dt><tt class="docutils literal"><span class="pre">node-id</span></tt></dt>
<dd>The node id written as a readable string as a hexadecimal number.</dd>
</dl>
<p><tt class="docutils literal">dht_state</tt> will return the current state of the dht node, this can be used
to start up the node again, passing this entry to <tt class="docutils literal">start_dht</tt>. It is a good
idea to save this to disk when the session is closed, and read it up again
when starting.</p>
<p>If the port the DHT is supposed to listen on is already in use, and exception
is thrown, <tt class="docutils literal"><span class="pre">asio::error</span></tt>.</p>
<p><tt class="docutils literal">stop_dht</tt> stops the dht node.</p>
<p><tt class="docutils literal">add_dht_node</tt> adds a node to the routing table. This can be used if your
client has its own source of bootstrapping nodes.</p>
<p><tt class="docutils literal">set_dht_settings</tt> sets some parameters availavle to the dht node. The
struct has the following members:</p>
<pre class="literal-block">
struct dht_settings
{
        int max_peers_reply;
        int search_branching;
        int max_fail_count;
        int max_torrents;
        bool restrict_routing_ips;
        bool restrict_search_ips;
        bool extended_routing_table;
        bool aggressive_lookups;
};
</pre>
<p><tt class="docutils literal">max_peers_reply</tt> is the maximum number of peers the node will send in
response to a <tt class="docutils literal">get_peers</tt> message from another node.</p>
<p><tt class="docutils literal">search_branching</tt> is the number of concurrent search request the node will
send when announcing and refreshing the routing table. This parameter is
called alpha in the kademlia paper.</p>
<p><tt class="docutils literal">max_fail_count</tt> is the maximum number of failed tries to contact a node
before it is removed from the routing table. If there are known working nodes
that are ready to replace a failing node, it will be replaced immediately,
this limit is only used to clear out nodes that don't have any node that can
replace them.</p>
<p><tt class="docutils literal">max_torrents</tt> is the total number of torrents to track from the DHT. This
is simply an upper limit to make sure malicious DHT nodes cannot make us allocate
an unbounded amount of memory.</p>
<p><tt class="docutils literal">max_feed_items</tt> is the total number of feed items to store from the DHT. This
is simply an upper limit to make sure malicious DHT nodes cannot make us allocate
an unbounded amount of memory.</p>
<p><tt class="docutils literal">restrict_routing_ips</tt> determines if the routing table entries should restrict
entries to one per IP. This defaults to true, which helps mitigate some attacks
on the DHT. It prevents adding multiple nodes with IPs with a very close CIDR
distance.</p>
<p><tt class="docutils literal">restrict_search_ips</tt> determines if DHT searches should prevent adding nodes
with IPs with very close CIDR distance. This also defaults to true and helps
mitigate certain attacks on the DHT.</p>
<p><tt class="docutils literal">extended_routing_table</tt> makes the first buckets in the DHT routing
table fit 128, 64, 32 and 16 nodes respectively, as opposed to the
standard size of 8. All other buckets have size 8 still.</p>
<p>The <tt class="docutils literal">dht_settings</tt> struct used to contain a <tt class="docutils literal">service_port</tt> member to control
which port the DHT would listen on and send messages from. This field is deprecated
and ignored. libtorrent always tries to open the UDP socket on the same port
as the TCP socket.</p>
<p><tt class="docutils literal">aggressive_lookups</tt> slightly changes the lookup behavior in terms of how
many outstanding requests we keep. Instead of having branch factor be a hard
limit, we always keep <em>branch factor</em> outstanding requests to the closest nodes.
i.e. every time we get results back with closer nodes, we query them right away.
It lowers the lookup times at the cost of more outstanding queries.</p>
<p><tt class="docutils literal">is_dht_running()</tt> returns true if the DHT support has been started and false
otherwise.</p>
</div>
<div class="section" id="add-dht-node-add-dht-router">
<h2>add_dht_node() add_dht_router()</h2>
<blockquote>
<pre class="literal-block">
void add_dht_node(std::pair&lt;std::string, int&gt; const&amp; node);
void add_dht_router(std::pair&lt;std::string, int&gt; const&amp; node);
</pre>
</blockquote>
<p><tt class="docutils literal">add_dht_node</tt> takes a host name and port pair. That endpoint will be
pinged, and if a valid DHT reply is received, the node will be added to
the routing table.</p>
<p><tt class="docutils literal">add_dht_router</tt> adds the given endpoint to a list of DHT router nodes.
If a search is ever made while the routing table is empty, those nodes will
be used as backups. Nodes in the router node list will also never be added
to the regular routing table, which effectively means they are only used
for bootstrapping, to keep the load off them.</p>
<p>An example routing node that you could typically add is
<tt class="docutils literal">router.bittorrent.com</tt>.</p>
</div>
<div class="section" id="start-lsd-stop-lsd">
<h2>start_lsd() stop_lsd()</h2>
<blockquote>
<pre class="literal-block">
void start_lsd();
void stop_lsd();
</pre>
</blockquote>
<p>Starts and stops Local Service Discovery. This service will broadcast
the infohashes of all the non-private torrents on the local network to
look for peers on the same swarm within multicast reach.</p>
<p>It is turned off by default.</p>
</div>
<div class="section" id="start-upnp-stop-upnp">
<h2>start_upnp() stop_upnp()</h2>
<blockquote>
<pre class="literal-block">
upnp* start_upnp();
void stop_upnp();
</pre>
</blockquote>
<p>Starts and stops the UPnP service. When started, the listen port and the DHT
port are attempted to be forwarded on local UPnP router devices.</p>
<p>The upnp object returned by <tt class="docutils literal">start_upnp()</tt> can be used to add and remove
arbitrary port mappings. Mapping status is returned through the
<a class="reference internal" href="#portmap-alert">portmap_alert</a> and the <a class="reference internal" href="#portmap-error-alert">portmap_error_alert</a>. The object will be valid until
<tt class="docutils literal">stop_upnp()</tt> is called. See <a class="reference internal" href="#upnp-and-nat-pmp">UPnP and NAT-PMP</a>.</p>
<p>It is off by default.</p>
</div>
<div class="section" id="start-natpmp-stop-natpmp">
<h2>start_natpmp() stop_natpmp()</h2>
<blockquote>
<pre class="literal-block">
natpmp* start_natpmp();
void stop_natpmp();
</pre>
</blockquote>
<p>Starts and stops the NAT-PMP service. When started, the listen port and the DHT
port are attempted to be forwarded on the router through NAT-PMP.</p>
<p>The natpmp object returned by <tt class="docutils literal">start_natpmp()</tt> can be used to add and remove
arbitrary port mappings. Mapping status is returned through the
<a class="reference internal" href="#portmap-alert">portmap_alert</a> and the <a class="reference internal" href="#portmap-error-alert">portmap_error_alert</a>. The object will be valid until
<tt class="docutils literal">stop_natpmp()</tt> is called. See <a class="reference internal" href="#upnp-and-nat-pmp">UPnP and NAT-PMP</a>.</p>
<p>It is off by default.</p>
</div>
</div>
<div class="section" id="entry">
<h1>entry</h1>
<p>The <tt class="docutils literal">entry</tt> class represents one node in a bencoded hierarchy. It works as a
variant type, it can be either a list, a dictionary (<tt class="docutils literal"><span class="pre">std::map</span></tt>), an integer
or a string. This is its synopsis:</p>
<pre class="literal-block">
class entry
{
public:

        typedef std::map&lt;std::string, entry&gt; dictionary_type;
        typedef std::string string_type;
        typedef std::list&lt;entry&gt; list_type;
        typedef size_type integer_type;

        enum data_type
        {
                int_t,
                string_t,
                list_t,
                dictionary_t,
                undefined_t
        };

        data_type type() const;

        entry(dictionary_type const&amp;);
        entry(string_type const&amp;);
        entry(list_type const&amp;);
        entry(integer_type const&amp;);

        entry();
        entry(data_type t);
        entry(entry const&amp; e);
        ~entry();

        void operator=(entry const&amp; e);
        void operator=(dictionary_type const&amp;);
        void operator=(string_type const&amp;);
        void operator=(list_type const&amp;);
        void operator=(integer_type const&amp;);

        integer_type&amp; integer();
        integer_type const&amp; integer() const;
        string_type&amp; string();
        string_type const&amp; string() const;
        list_type&amp; list();
        list_type const&amp; list() const;
        dictionary_type&amp; dict();
        dictionary_type const&amp; dict() const;

        // these functions requires that the entry
        // is a dictionary, otherwise they will throw
        entry&amp; operator[](char const* key);
        entry&amp; operator[](std::string const&amp; key);
        entry const&amp; operator[](char const* key) const;
        entry const&amp; operator[](std::string const&amp; key) const;
        entry* find_key(char const* key);
        entry const* find_key(char const* key) const;

        void print(std::ostream&amp; os, int indent = 0) const;
};
</pre>
<p><em>TODO: finish documentation of entry.</em></p>
<div class="section" id="integer-string-list-dict-type">
<h2>integer() string() list() dict() type()</h2>
<blockquote>
<pre class="literal-block">
integer_type&amp; integer();
integer_type const&amp; integer() const;
string_type&amp; string();
string_type const&amp; string() const;
list_type&amp; list();
list_type const&amp; list() const;
dictionary_type&amp; dict();
dictionary_type const&amp; dict() const;
</pre>
</blockquote>
<p>The <tt class="docutils literal">integer()</tt>, <tt class="docutils literal">string()</tt>, <tt class="docutils literal">list()</tt> and <tt class="docutils literal">dict()</tt> functions
are accessors that return the respective type. If the <tt class="docutils literal">entry</tt> object isn't of the
type you request, the accessor will throw <a class="reference internal" href="#libtorrent-exception">libtorrent_exception</a> (which derives from
<tt class="docutils literal"><span class="pre">std::runtime_error</span></tt>). You can ask an <tt class="docutils literal">entry</tt> for its type through the
<tt class="docutils literal">type()</tt> function.</p>
<p>The <tt class="docutils literal">print()</tt> function is there for debug purposes only.</p>
<p>If you want to create an <tt class="docutils literal">entry</tt> you give it the type you want it to have in its
constructor, and then use one of the non-const accessors to get a reference which you then
can assign the value you want it to have.</p>
<p>The typical code to get info from a torrent file will then look like this:</p>
<pre class="literal-block">
entry torrent_file;
// ...

// throws if this is not a dictionary
entry::dictionary_type const&amp; dict = torrent_file.dict();
entry::dictionary_type::const_iterator i;
i = dict.find(&quot;announce&quot;);
if (i != dict.end())
{
        std::string tracker_url = i-&gt;second.string();
        std::cout &lt;&lt; tracker_url &lt;&lt; &quot;\n&quot;;
}
</pre>
<p>The following code is equivalent, but a little bit shorter:</p>
<pre class="literal-block">
entry torrent_file;
// ...

// throws if this is not a dictionary
if (entry* i = torrent_file.find_key(&quot;announce&quot;))
{
        std::string tracker_url = i-&gt;string();
        std::cout &lt;&lt; tracker_url &lt;&lt; &quot;\n&quot;;
}
</pre>
<p>To make it easier to extract information from a torrent file, the class <a class="reference internal" href="#torrent-info">torrent_info</a>
exists.</p>
</div>
<div class="section" id="operator">
<h2>operator[]</h2>
<blockquote>
<pre class="literal-block">
entry&amp; operator[](char const* key);
entry&amp; operator[](std::string const&amp; key);
entry const&amp; operator[](char const* key) const;
entry const&amp; operator[](std::string const&amp; key) const;
</pre>
</blockquote>
<p>All of these functions requires the entry to be a dictionary, if it isn't they
will throw <tt class="docutils literal"><span class="pre">libtorrent::type_error</span></tt>.</p>
<p>The non-const versions of the <tt class="docutils literal">operator[]</tt> will return a reference to either
the existing element at the given key or, if there is no element with the
given key, a reference to a newly inserted element at that key.</p>
<p>The const version of <tt class="docutils literal">operator[]</tt> will only return a reference to an
existing element at the given key. If the key is not found, it will throw
<tt class="docutils literal"><span class="pre">libtorrent::type_error</span></tt>.</p>
</div>
<div class="section" id="find-key">
<h2>find_key()</h2>
<blockquote>
<pre class="literal-block">
entry* find_key(char const* key);
entry const* find_key(char const* key) const;
</pre>
</blockquote>
<p>These functions requires the entry to be a dictionary, if it isn't they
will throw <tt class="docutils literal"><span class="pre">libtorrent::type_error</span></tt>.</p>
<p>They will look for an element at the given key in the dictionary, if the
element cannot be found, they will return 0. If an element with the given
key is found, the return a pointer to it.</p>
</div>
</div>
<div class="section" id="torrent-info">
<h1>torrent_info</h1>
<p>In previous versions of libtorrent, this class was also used for creating
torrent files. This functionality has been moved to <tt class="docutils literal">create_torrent</tt>, see
<a class="reference external" href="make_torrent.html">make_torrent</a>.</p>
<p>The <tt class="docutils literal">torrent_info</tt> has the following synopsis:</p>
<pre class="literal-block">
class torrent_info
{
public:

        // these constructors throws exceptions on error
        torrent_info(sha1_hash const&amp; info_hash, int flags = 0);
        torrent_info(lazy_entry const&amp; torrent_file, int flags = 0);
        torrent_info(char const* buffer, int size, int flags = 0);
        torrent_info(std::string const&amp; filename, int flags = 0);
        torrent_info(std::wstring const&amp; filename, int flags = 0);

        // these constructors sets the error code on error
        torrent_info(sha1_hash const&amp; info_hash, error_code&amp; ec, int flags = 0);
        torrent_info(lazy_entry const&amp; torrent_file, error_code&amp; ec, int flags = 0);
        torrent_info(char const* buffer, int size, error_code&amp; ec, int flags = 0);
        torrent_info(fs::path const&amp; filename, error_code&amp; ec, int flags = 0);
        torrent_info(fs::wpath const&amp; filename, error_code&amp; ec, int flags = 0);

        void add_tracker(std::string const&amp; url, int tier = 0);
        std::vector&lt;announce_entry&gt; const&amp; trackers() const;

        file_storage const&amp; files() const;
        file_storage const&amp; orig_files() const;

        void remap_files(file_storage const&amp; f);

        void rename_file(int index, std::string const&amp; new_filename);
        void rename_file(int index, std::wstring const&amp; new_filename);

        typedef file_storage::iterator file_iterator;
        typedef file_storage::reverse_iterator reverse_file_iterator;

        file_iterator begin_files() const;
        file_iterator end_files() const;
        reverse_file_iterator rbegin_files() const;
        reverse_file_iterator rend_files() const;

        int num_files() const;
        file_entry const&amp; file_at(int index) const;

        std::vector&lt;file_slice&gt; map_block(int piece, size_type offset
                , int size) const;
        peer_request map_file(int file_index, size_type file_offset
                , int size) const;

        bool priv() const;

        void add_url_seed(std::string const&amp; url);
        void add_http_seed(std::string const&amp; url);
        std::vector&lt;web_seed_entry&gt; const&amp; web_seeds() const;

        size_type total_size() const;
        int piece_length() const;
        int num_pieces() const;
        sha1_hash const&amp; info_hash() const;
        std::string const&amp; name() const;
        std::string const&amp; comment() const;
        std::string const&amp; creator() const;

        std::vector&lt;std::pair&lt;std::string, int&gt; &gt; const&amp; nodes() const;
        void add_node(std::pair&lt;std::string, int&gt; const&amp; node);

        boost::optional&lt;time_t&gt; creation_date() const;

        int piece_size(unsigned int index) const;
        sha1_hash const&amp; hash_for_piece(unsigned int index) const;
        char const* hash_for_piece_ptr(unsigned int index) const;

        std::vector&lt;sha1_hash&gt; const&amp; merkle_tree() const;
        void set_merkle_tree(std::vector&lt;sha1_hash&gt;&amp; h);

        boost::shared_array&lt;char&gt; metadata() const;
        int metadata_size() const;
};
</pre>
<div class="section" id="id3">
<h2>torrent_info()</h2>
<blockquote>
<pre class="literal-block">
torrent_info(sha1_hash const&amp; info_hash, int flags = 0);
torrent_info(lazy_entry const&amp; torrent_file, int flags = 0);
torrent_info(char const* buffer, int size, int flags = 0);
torrent_info(std::string const&amp; filename, int flags = 0);
torrent_info(std::wstring const&amp; filename, int flags = 0);

torrent_info(sha1_hash const&amp; info_hash, error_code&amp; ec, int flags = 0);
torrent_info(lazy_entry const&amp; torrent_file, error_code&amp; ec, int flags = 0);
torrent_info(char const* buffer, int size, error_code&amp; ec, int flags = 0);
torrent_info(fs::path const&amp; filename, error_code&amp; ec, int flags = 0);
torrent_info(fs::wpath const&amp; filename, error_code&amp; ec, int flags = 0);
</pre>
</blockquote>
<p>The constructor that takes an info-hash  will initialize the info-hash to the given value,
but leave all other fields empty. This is used internally when downloading torrents without
the metadata. The metadata will be created by libtorrent as soon as it has been downloaded
from the swarm.</p>
<p>The constructor that takes a <tt class="docutils literal">lazy_entry</tt> will create a <tt class="docutils literal">torrent_info</tt> object from the
information found in the given torrent_file. The <tt class="docutils literal">lazy_entry</tt> represents a tree node in
an bencoded file. To load an ordinary .torrent file
into a <tt class="docutils literal">lazy_entry</tt>, use <a class="reference internal" href="#lazy-bdecode">lazy_bdecode()</a>.</p>
<p>The version that takes a buffer pointer and a size will decode it as a .torrent file and
initialize the torrent_info object for you.</p>
<p>The version that takes a filename will simply load the torrent file and decode it inside
the constructor, for convenience. This might not be the most suitable for applications that
want to be able to report detailed errors on what might go wrong.</p>
<p>The overloads that takes an <tt class="docutils literal">error_code const&amp;</tt> never throws if an error occur, they
will simply set the error code to describe what went wrong and not fully initialize the
torrent_info object. The overloads that do not take the extra <a class="reference internal" href="#error-code">error_code</a> parameter will
always throw if an error occurs. These overloads are not available when building without
exception support.</p>
<p>The <tt class="docutils literal">flags</tt> argument is currently unused.</p>
</div>
<div class="section" id="add-tracker">
<h2>add_tracker()</h2>
<blockquote>
<pre class="literal-block">
void add_tracker(std::string const&amp; url, int tier = 0);
</pre>
</blockquote>
<p><tt class="docutils literal">add_tracker()</tt> adds a tracker to the announce-list. The <tt class="docutils literal">tier</tt> determines the order in
which the trackers are to be tried. For more information see <a class="reference internal" href="#trackers">trackers()</a>.</p>
</div>
<div class="section" id="files-orig-files">
<h2>files() orig_files()</h2>
<blockquote>
<pre class="literal-block">
file_storage const&amp; files() const;
file_storage const&amp; orig_files() const;
</pre>
</blockquote>
<p>The <tt class="docutils literal">file_storage</tt> object contains the information on how to map the pieces to
files. It is separated from the <tt class="docutils literal">torrent_info</tt> object because when creating torrents
a storage object needs to be created without having a torrent file. When renaming files
in a storage, the storage needs to make its own copy of the <tt class="docutils literal">file_storage</tt> in order
to make its mapping differ from the one in the torrent file.</p>
<p><tt class="docutils literal">orig_files()</tt> returns the original (unmodified) file storage for this torrent. This
is used by the web server connection, which needs to request files with the original
names. Filename may be chaged using <tt class="docutils literal"><span class="pre">torrent_info::rename_file()</span></tt>.</p>
<p>For more information on the <tt class="docutils literal">file_storage</tt> object, see the separate document on how
to create torrents.</p>
</div>
<div class="section" id="remap-files">
<h2>remap_files()</h2>
<blockquote>
<pre class="literal-block">
void remap_files(file_storage const&amp; f);
</pre>
</blockquote>
<p>Remaps the file storage to a new file layout. This can be used to, for instance,
download all data in a torrent to a single file, or to a number of fixed size
sector aligned files, regardless of the number and sizes of the files in the torrent.</p>
<p>The new specified <tt class="docutils literal">file_storage</tt> must have the exact same size as the current one.</p>
</div>
<div class="section" id="rename-file">
<h2>rename_file()</h2>
<blockquote>
<pre class="literal-block">
void rename_file(int index, std::string const&amp; new_filename);
void rename_file(int index, std::wstring const&amp; new_filename);
</pre>
</blockquote>
<p>Renames a the file with the specified index to the new name. The new filename is
reflected by the <tt class="docutils literal">file_storage</tt> returned by <tt class="docutils literal">files()</tt> but not by the one
returned by <tt class="docutils literal">orig_files()</tt>.</p>
<p>If you want to rename the base name of the torrent (for a multifile torrent), you
can copy the <tt class="docutils literal">file_storage</tt> (see <a class="reference internal" href="#files-orig-files">files() orig_files()</a>), change the name, and
then use <a class="reference internal" href="#remap-files">remap_files()</a>.</p>
</div>
<div class="section" id="begin-files-end-files-rbegin-files-rend-files">
<h2>begin_files() end_files() rbegin_files() rend_files()</h2>
<blockquote>
<pre class="literal-block">
file_iterator begin_files() const;
file_iterator end_files() const;
reverse_file_iterator rbegin_files() const;
reverse_file_iterator rend_files() const;
</pre>
</blockquote>
<p>This class will need some explanation. First of all, to get a list of all files
in the torrent, you can use <tt class="docutils literal">begin_files()</tt>, <tt class="docutils literal">end_files()</tt>,
<tt class="docutils literal">rbegin_files()</tt> and <tt class="docutils literal">rend_files()</tt>. These will give you standard vector
iterators with the type <tt class="docutils literal">internal_file_entry</tt>, which is an internal type.</p>
<p>You can resolve it into the public representation of a file (<tt class="docutils literal">file_entry</tt>)
using the <tt class="docutils literal"><span class="pre">file_storage::at</span></tt> function, which takes an index and an iterator;</p>
<pre class="literal-block">
struct file_entry
{
        std::string path;
        size_type offset;
        size_type size;
        size_type file_base;
        time_t mtime;
        sha1_hash filehash;
        bool pad_file:1;
        bool hidden_attribute:1;
        bool executable_attribute:1;
        bool symlink_attribute:1;
};
</pre>
<p>The <tt class="docutils literal">path</tt> is the full path of this file. The paths are unicode strings
encoded in UTF-8.</p>
<p><tt class="docutils literal">size</tt> is the size of the file (in bytes) and <tt class="docutils literal">offset</tt> is the byte offset
of the file within the torrent. i.e. the sum of all the sizes of the files
before it in the list.</p>
<p><tt class="docutils literal">file_base</tt> is the offset in the file where the storage should start. The normal
case is to have this set to 0, so that the storage starts saving data at the start
if the file. In cases where multiple files are mapped into the same file though,
the <tt class="docutils literal">file_base</tt> should be set to an offset so that the different regions do
not overlap. This is used when mapping &quot;unselected&quot; files into a so-called part
file.</p>
<p><tt class="docutils literal">mtime</tt> is the modification time of this file specified in posix time.</p>
<p><tt class="docutils literal">symlink_path</tt> is the path which this is a symlink to, or empty if this is
not a symlink. This field is only used if the <tt class="docutils literal">symlink_attribute</tt> is set.</p>
<p><tt class="docutils literal">filehash</tt> is a sha-1 hash of the content of the file, or zeroes, if no
file hash was present in the torrent file. It can be used to potentially
find alternative sources for the file.</p>
<p><tt class="docutils literal">pad_file</tt> is set to true for files that are not part of the data of the torrent.
They are just there to make sure the next file is aligned to a particular byte offset
or piece boundry. These files should typically be hidden from an end user. They are
not written to disk.</p>
<p><tt class="docutils literal">hidden_attribute</tt> is true if the file was marked as hidden (on windows).</p>
<p><tt class="docutils literal">executable_attribute</tt> is true if the file was marked as executable (posix)</p>
<p><tt class="docutils literal">symlink_attribute</tt> is true if the file was a symlink. If this is the case
the <tt class="docutils literal">symlink_index</tt> refers to a string which specifies the original location
where the data for this file was found.</p>
</div>
<div class="section" id="num-files-file-at">
<h2>num_files() file_at()</h2>
<blockquote>
<pre class="literal-block">
int num_files() const;
file_entry const&amp; file_at(int index) const;
</pre>
</blockquote>
<p>If you need index-access to files you can use the <tt class="docutils literal">num_files()</tt> and <tt class="docutils literal">file_at()</tt>
to access files using indices.</p>
</div>
<div class="section" id="map-block">
<h2>map_block()</h2>
<blockquote>
<pre class="literal-block">
std::vector&lt;file_slice&gt; map_block(int piece, size_type offset
        , int size) const;
</pre>
</blockquote>
<p>This function will map a piece index, a byte offset within that piece and
a size (in bytes) into the corresponding files with offsets where that data
for that piece is supposed to be stored.</p>
<p>The file slice struct looks like this:</p>
<pre class="literal-block">
struct file_slice
{
        int file_index;
        size_type offset;
        size_type size;
};
</pre>
<p>The <tt class="docutils literal">file_index</tt> refers to the index of the file (in the torrent_info).
To get the path and filename, use <tt class="docutils literal">file_at()</tt> and give the <tt class="docutils literal">file_index</tt>
as argument. The <tt class="docutils literal">offset</tt> is the byte offset in the file where the range
starts, and <tt class="docutils literal">size</tt> is the number of bytes this range is. The size + offset
will never be greater than the file size.</p>
</div>
<div class="section" id="map-file">
<h2>map_file()</h2>
<blockquote>
<pre class="literal-block">
peer_request map_file(int file_index, size_type file_offset
        , int size) const;
</pre>
</blockquote>
<p>This function will map a range in a specific file into a range in the torrent.
The <tt class="docutils literal">file_offset</tt> parameter is the offset in the file, given in bytes, where
0 is the start of the file.
The <tt class="docutils literal">peer_request</tt> structure looks like this:</p>
<pre class="literal-block">
struct peer_request
{
        int piece;
        int start;
        int length;
        bool operator==(peer_request const&amp; r) const;
};
</pre>
<p><tt class="docutils literal">piece</tt> is the index of the piece in which the range starts.
<tt class="docutils literal">start</tt> is the offset within that piece where the range starts.
<tt class="docutils literal">length</tt> is the size of the range, in bytes.</p>
<p>The input range is assumed to be valid within the torrent. <tt class="docutils literal">file_offset</tt>
+ <tt class="docutils literal">size</tt> is not allowed to be greater than the file size. <tt class="docutils literal">file_index</tt>
must refer to a valid file, i.e. it cannot be &gt;= <tt class="docutils literal">num_files()</tt>.</p>
</div>
<div class="section" id="add-url-seed-add-http-seed">
<h2>add_url_seed() add_http_seed()</h2>
<blockquote>
<pre class="literal-block">
void add_url_seed(std::string const&amp; url
        , std::string const&amp; extern_auth = std::string()
        , web_seed_entry::headers_t const&amp; extra_headers = web_seed_entry::headers_t());
void add_http_seed(std::string const&amp; url
        , std::string const&amp; extern_auth = std::string()
        , web_seed_entry::headers_t const&amp; extra_headers = web_seed_entry::headers_t());
std::vector&lt;web_seed_entry&gt; const&amp; web_seeds() const;
</pre>
</blockquote>
<p><tt class="docutils literal">web_seeds()</tt> returns all url seeds and http seeds in the torrent. Each entry
is a <tt class="docutils literal">web_seed_entry</tt> and may refer to either a url seed or http seed.</p>
<p><tt class="docutils literal">add_url_seed()</tt> and <tt class="docutils literal">add_http_seed()</tt> adds one url to the list of
url/http seeds. Currently, the only transport protocol supported for the url
is http.</p>
<p>The <tt class="docutils literal">extern_auth</tt> argument can be used for other athorization schemese than
basic HTTP authorization. If set, it will override any username and password
found in the URL itself. The string will be sent as the HTTP authorization header's
value (without specifying &quot;Basic&quot;).</p>
<p>The <tt class="docutils literal">extra_headers</tt> argument defaults to an empty list, but can be used to
insert custom HTTP headers in the requests to a specific web seed.</p>
<p>See <a class="reference internal" href="#http-seeding">HTTP seeding</a> for more information.</p>
<p>The <tt class="docutils literal">web_seed_entry</tt> has the following members:</p>
<pre class="literal-block">
struct web_seed_entry
{
        enum type_t { url_seed, http_seed };

        typedef std::vector&lt;std::pair&lt;std::string, std::string&gt; &gt; headers_t;

        web_seed_entry(std::string const&amp; url_, type_t type_
                , std::string const&amp; auth_ = std::string()
                , headers_t const&amp; extra_headers_ = headers_t());

        bool operator==(web_seed_entry const&amp; e) const;
        bool operator&lt;(web_seed_entry const&amp; e) const;

        std::string url;
        type_t type;
        std::string auth;
        headers_t extra_headers;

        // ...
};
</pre>
</div>
<div class="section" id="trackers">
<h2>trackers()</h2>
<blockquote>
<pre class="literal-block">
std::vector&lt;announce_entry&gt; const&amp; trackers() const;
</pre>
</blockquote>
<p>The <tt class="docutils literal">trackers()</tt> function will return a sorted vector of <tt class="docutils literal">announce_entry</tt>.
Each announce entry contains a string, which is the tracker url, and a tier index. The
tier index is the high-level priority. No matter which trackers that works or not, the
ones with lower tier will always be tried before the one with higher tier number.</p>
<pre class="literal-block">
struct announce_entry
{
        announce_entry(std::string const&amp; url);
        std::string url;

        int next_announce_in() const;
        int min_announce_in() const;

        error_code last_error;

        std::string message;

        boost::uint8_t tier;
        boost::uint8_t fail_limit;
        boost::uint8_t fails;

        enum tracker_source
        {
                source_torrent = 1,
                source_client = 2,
                source_magnet_link = 4,
                source_tex = 8
        };
        boost::uint8_t source;

        bool verified:1;
        bool updating:1;
        bool start_sent:1;
        bool complete_sent:1;
};
</pre>
<p><tt class="docutils literal">next_announce_in()</tt> returns the number of seconds to the next announce on
this tracker. <tt class="docutils literal">min_announce_in()</tt> returns the number of seconds until we are
allowed to force another tracker update with this tracker.</p>
<p>If the last time this tracker was contacted failed, <tt class="docutils literal">last_error</tt> is the error
code describing what error occurred.</p>
<p>If the last time this tracker was contacted, the tracker returned a warning
or error message, <tt class="docutils literal">message</tt> contains that message.</p>
<p><tt class="docutils literal">fail_limit</tt> is the max number of failures to announce to this tracker in
a row, before this tracker is not used anymore.</p>
<p><tt class="docutils literal">fails</tt> is the number of times in a row we have failed to announce to this
tracker.</p>
<p><tt class="docutils literal">source</tt> is a bitmask specifying which sources we got this tracker from.</p>
<p><tt class="docutils literal">verified</tt> is set to true the first time we receive a valid response
from this tracker.</p>
<p><tt class="docutils literal">updating</tt> is true while we're waiting for a response from the tracker.</p>
<p><tt class="docutils literal">start_sent</tt> is set to true when we get a valid response from an announce
with event=started. If it is set, we won't send start in the subsequent
announces.</p>
<p><tt class="docutils literal">complete_sent</tt> is set to true when we send a event=completed.</p>
</div>
<div class="section" id="total-size-piece-length-piece-size-num-pieces">
<h2>total_size() piece_length() piece_size() num_pieces()</h2>
<blockquote>
<pre class="literal-block">
size_type total_size() const;
int piece_length() const;
int piece_size(unsigned int index) const;
int num_pieces() const;
</pre>
</blockquote>
<p><tt class="docutils literal">total_size()</tt>, <tt class="docutils literal">piece_length()</tt> and <tt class="docutils literal">num_pieces()</tt> returns the total
number of bytes the torrent-file represents (all the files in it), the number of byte for
each piece and the total number of pieces, respectively. The difference between
<tt class="docutils literal">piece_size()</tt> and <tt class="docutils literal">piece_length()</tt> is that <tt class="docutils literal">piece_size()</tt> takes
the piece index as argument and gives you the exact size of that piece. It will always
be the same as <tt class="docutils literal">piece_length()</tt> except in the case of the last piece, which may
be smaller.</p>
</div>
<div class="section" id="hash-for-piece-hash-for-piece-ptr-info-hash">
<h2>hash_for_piece() hash_for_piece_ptr() info_hash()</h2>
<blockquote>
<pre class="literal-block">
size_type piece_size(unsigned int index) const;
sha1_hash const&amp; hash_for_piece(unsigned int index) const;
char const* hash_for_piece_ptr(unsigned int index) const;
</pre>
</blockquote>
<p><tt class="docutils literal">hash_for_piece()</tt> takes a piece-index and returns the 20-bytes sha1-hash for that
piece and <tt class="docutils literal">info_hash()</tt> returns the 20-bytes sha1-hash for the info-section of the
torrent file. For more information on the <tt class="docutils literal">sha1_hash</tt>, see the <a class="reference internal" href="#big-number">big_number</a> class.
<tt class="docutils literal">hash_for_piece_ptr()</tt> returns a pointer to the 20 byte sha1 digest for the piece.
Note that the string is not null-terminated.</p>
</div>
<div class="section" id="merkle-tree-set-merkle-tree">
<h2>merkle_tree() set_merkle_tree()</h2>
<blockquote>
<pre class="literal-block">
std::vector&lt;sha1_hash&gt; const&amp; merkle_tree() const;
void set_merkle_tree(std::vector&lt;sha1_hash&gt;&amp; h);
</pre>
</blockquote>
<p><tt class="docutils literal">merkle_tree()</tt> returns a reference to the merkle tree for this torrent, if any.</p>
<p><tt class="docutils literal">set_merkle_tree()</tt> moves the passed in merkle tree into the torrent_info object.
i.e. <tt class="docutils literal">h</tt> will not be identical after the call. You need to set the merkle tree for
a torrent that you've just created (as a merkle torrent). The merkle tree is retrieved
from the <tt class="docutils literal"><span class="pre">create_torrent::merkle_tree()</span></tt> function, and need to be saved separately
from the torrent file itself. Once it's added to libtorrent, the merkle tree will be
persisted in the resume data.</p>
</div>
<div class="section" id="name-comment-creation-date-creator">
<h2>name() comment() creation_date() creator()</h2>
<blockquote>
<pre class="literal-block">
std::string const&amp; name() const;
std::string const&amp; comment() const;
std::string const&amp; creator() const;
boost::optional&lt;time_t&gt; creation_date() const;
</pre>
</blockquote>
<p><tt class="docutils literal">name()</tt> returns the name of the torrent.</p>
<p><tt class="docutils literal">comment()</tt> returns the comment associated with the torrent. If there's no comment,
it will return an empty string. <tt class="docutils literal">creation_date()</tt> returns the creation date of
the torrent as time_t (<a class="reference external" href="http://www.opengroup.org/onlinepubs/009695399/functions/time.html">posix time</a>). If there's no time stamp in the torrent file,
the optional object will be uninitialized.</p>
<p>Both the name and the comment is UTF-8 encoded strings.</p>
<p><tt class="docutils literal">creator()</tt> returns the creator string in the torrent. If there is no creator string
it will return an empty string.</p>
</div>
<div class="section" id="priv">
<h2>priv()</h2>
<blockquote>
<pre class="literal-block">
bool priv() const;
</pre>
</blockquote>
<p><tt class="docutils literal">priv()</tt> returns true if this torrent is private. i.e., it should not be
distributed on the trackerless network (the kademlia DHT).</p>
</div>
<div class="section" id="nodes">
<h2>nodes()</h2>
<blockquote>
<pre class="literal-block">
std::vector&lt;std::pair&lt;std::string, int&gt; &gt; const&amp; nodes() const;
</pre>
</blockquote>
<p>If this torrent contains any DHT nodes, they are put in this vector in their original
form (host name and port number).</p>
</div>
<div class="section" id="add-node">
<h2>add_node()</h2>
<blockquote>
<pre class="literal-block">
void add_node(std::pair&lt;std::string, int&gt; const&amp; node);
</pre>
</blockquote>
<p>This is used when creating torrent. Use this to add a known DHT node. It may
be used, by the client, to bootstrap into the DHT network.</p>
</div>
<div class="section" id="metadata-metadata-size">
<h2>metadata() metadata_size()</h2>
<blockquote>
<pre class="literal-block">
boost::shared_array&lt;char&gt; metadata() const;
int metadata_size() const;
</pre>
</blockquote>
<p><tt class="docutils literal">metadata()</tt> returns a the raw info section of the torrent file. The size
of the metadata is returned by <tt class="docutils literal">metadata_size()</tt>.</p>
</div>
</div>
<div class="section" id="torrent-handle">
<h1>torrent_handle</h1>
<p>You will usually have to store your torrent handles somewhere, since it's the
object through which you retrieve information about the torrent and aborts the torrent.</p>
<div class="warning">
<p class="first admonition-title">Warning</p>
<p class="last">Any member function that returns a value or fills in a value has to
be made synchronously. This means it has to wait for the main thread
to complete the query before it can return. This might potentially be
expensive if done from within a GUI thread that needs to stay responsive.
Try to avoid quering for information you don't need, and try to do it
in as few calls as possible. You can get most of the interesting information
about a torrent from the <tt class="docutils literal"><span class="pre">torrent_handle::status()</span></tt> call.</p>
</div>
<p>Its declaration looks like this:</p>
<pre class="literal-block">
struct torrent_handle
{
        torrent_handle();

        enum status_flags_t
        {
                query_distributed_copies = 1,
                query_accurate_download_counters = 2,
                query_last_seen_complete = 4,
                query_pieces = 8,
                query_verified_pieces = 16
        };

        torrent_status status(boost::uint32_t flags = 0xffffffff);
        void file_progress(std::vector&lt;size_type&gt;&amp; fp, int flags = 0);
        void get_download_queue(std::vector&lt;partial_piece_info&gt;&amp; queue) const;
        void get_peer_info(std::vector&lt;peer_info&gt;&amp; v) const;
        boost::intrusive_ptr&lt;torrent_info&gt; torrent_file() const;
        bool is_valid() const;

        std::string name() const;

        enum save_resume_flags_t { flush_disk_cache = 1, save_info_dict = 2 };
        void save_resume_data(int flags = 0) const;
        bool need_save_resume_data() const;
        void force_reannounce() const;
        void force_dht_announce() const;
        void force_reannounce(boost::posix_time::time_duration) const;
        void scrape_tracker() const;
        void connect_peer(asio::ip::tcp::endpoint const&amp; adr, int source = 0) const;

        void set_tracker_login(std::string const&amp; username
                , std::string const&amp; password) const;

        std::vector&lt;announce_entry&gt; trackers() const;
        void replace_trackers(std::vector&lt;announce_entry&gt; const&amp;);
        void add_tracker(announce_entry const&amp; url);

        void add_url_seed(std::string const&amp; url);
        void remove_url_seed(std::string const&amp; url);
        std::set&lt;std::string&gt; url_seeds() const;

        void add_http_seed(std::string const&amp; url);
        void remove_http_seed(std::string const&amp; url);
        std::set&lt;std::string&gt; http_seeds() const;

        int max_uploads() const;
        void set_max_uploads(int max_uploads) const;
        void set_max_connections(int max_connections) const;
        int max_connections() const;
        void set_upload_limit(int limit) const;
        int upload_limit() const;
        void set_download_limit(int limit) const;
        int download_limit() const;
        void set_sequential_download(bool sd) const;
        bool is_sequential_download() const;

        int queue_position() const;
        void queue_position_up() const;
        void queue_position_down() const;
        void queue_position_top() const;
        void queue_position_bottom() const;

        void set_priority(int prio) const;

        void use_interface(char const* net_interface) const;

        enum pause_flags_t { graceful_pause = 1 };
        void pause(int flags = 0) const;
        void resume() const;
        bool is_seed() const;
        void force_recheck() const;
        void clear_error() const;
        void set_upload_mode(bool m) const;
        void set_share_mode(bool m) const;

        void apply_ip_filter(bool b) const;

        void flush_cache() const;

        void resolve_countries(bool r);
        bool resolve_countries() const;

        enum deadline_flags { alert_when_available = 1 };
        void set_piece_deadline(int index, int deadline, int flags = 0) const;
        void reset_piece_deadline(int index) const;

        void piece_availability(std::vector&lt;int&gt;&amp; avail) const;
        void piece_priority(int index, int priority) const;
        int piece_priority(int index) const;
        void prioritize_pieces(std::vector&lt;int&gt; const&amp; pieces) const;
        std::vector&lt;int&gt; piece_priorities() const;

        void file_priority(int index, int priority) const;
        int file_priority(int index) const;
        void prioritize_files(std::vector&lt;int&gt; const&amp; files) const;
        std::vector&lt;int&gt; file_priorities() const;

        void auto_managed(bool m) const;

        bool set_metadata(char const* buf, int size) const;

        std::string save_path() const;
        void move_storage(std::string const&amp; save_path) const;
        void move_storage(std::wstring const&amp; save_path) const;
        void rename_file(int index, std::string) const;
        void rename_file(int index, std::wstring) const;
        storage_interface* get_storage_impl() const;

        void super_seeding(bool on) const;

        enum flags_t { overwrite_existing = 1 };
        void add_piece(int piece, char const* data, int flags = 0) const;
        void read_piece(int piece) const;
        bool have_piece(int piece) const;

        sha1_hash info_hash() const;

        void set_ssl_certificate(std::string const&amp; cert
                , std::string const&amp; private_key
                , std::string const&amp; dh_params
                , std::string const&amp; passphrase = &quot;&quot;);

        bool operator==(torrent_handle const&amp;) const;
        bool operator!=(torrent_handle const&amp;) const;
        bool operator&lt;(torrent_handle const&amp;) const;

        boost::shared_ptr&lt;torrent&gt; native_handle() const;
};
</pre>
<p>The default constructor will initialize the handle to an invalid state. Which
means you cannot perform any operation on it, unless you first assign it a
valid handle. If you try to perform any operation on an uninitialized handle,
it will throw <tt class="docutils literal">invalid_handle</tt>.</p>
<div class="warning">
<p class="first admonition-title">Warning</p>
<p class="last">All operations on a <tt class="docutils literal">torrent_handle</tt> may throw <a class="reference internal" href="#libtorrent-exception">libtorrent_exception</a>
exception, in case the handle is no longer refering to a torrent. There is
one exception <tt class="docutils literal">is_valid()</tt> will never throw.
Since the torrents are processed by a background thread, there is no
guarantee that a handle will remain valid between two calls.</p>
</div>
<div class="section" id="set-piece-deadline-reset-piece-deadline">
<h2>set_piece_deadline() reset_piece_deadline()</h2>
<blockquote>
<pre class="literal-block">
enum deadline_flags { alert_when_available = 1 };
void set_piece_deadline(int index, int deadline, int flags = 0) const;
void reset_piece_deadline(int index) const;
</pre>
</blockquote>
<p>This function sets or resets the deadline associated with a specific piece
index (<tt class="docutils literal">index</tt>). libtorrent will attempt to download this entire piece before
the deadline expires. This is not necessarily possible, but pieces with a more
recent deadline will always be prioritized over pieces with a deadline further
ahead in time. The deadline (and flags) of a piece can be changed by calling this
function again.</p>
<p>The <tt class="docutils literal">flags</tt> parameter can be used to ask libtorrent to send an alert once the
piece has been downloaded, by passing <tt class="docutils literal">alert_when_available</tt>. When set, the
<a class="reference internal" href="#read-piece-alert">read_piece_alert</a> alert will be delivered, with the piece data, when it's downloaded.</p>
<p>If the piece is already downloaded when this call is made, nothing happens, unless
the <tt class="docutils literal">alert_when_available</tt> flag is set, in which case it will do the same thing
as calling <a class="reference internal" href="#read-piece">read_piece()</a> for <tt class="docutils literal">index</tt>.</p>
<p><tt class="docutils literal">deadline</tt> is the number of milliseconds until this piece should be completed.</p>
<p><tt class="docutils literal">reset_piece_deadline</tt> removes the deadline from the piece. If it hasn't already
been downloaded, it will no longer be considered a priority.</p>
</div>
<div class="section" id="piece-availability">
<h2>piece_availability()</h2>
<blockquote>
<pre class="literal-block">
void piece_availability(std::vector&lt;int&gt;&amp; avail) const;
</pre>
</blockquote>
<p>Fills the specified <tt class="docutils literal"><span class="pre">std::vector&lt;int&gt;</span></tt> with the availability for each
piece in this torrent. libtorrent does not keep track of availability for
seeds, so if the torrent is seeding the availability for all pieces is
reported as 0.</p>
<p>The piece availability is the number of peers that we are connected that has
advertized having a particular piece. This is the information that libtorrent
uses in order to prefer picking rare pieces.</p>
</div>
<div class="section" id="piece-priority-prioritize-pieces-piece-priorities">
<h2>piece_priority() prioritize_pieces() piece_priorities()</h2>
<blockquote>
<pre class="literal-block">
void piece_priority(int index, int priority) const;
int piece_priority(int index) const;
void prioritize_pieces(std::vector&lt;int&gt; const&amp; pieces) const;
std::vector&lt;int&gt; piece_priorities() const;
</pre>
</blockquote>
<p>These functions are used to set and get the prioritiy of individual pieces.
By default all pieces have priority 1. That means that the random rarest
first algorithm is effectively active for all pieces. You may however
change the priority of individual pieces. There are 8 different priority
levels:</p>
<blockquote>
<ol class="arabic simple" start="0">
<li>piece is not downloaded at all</li>
<li>normal priority. Download order is dependent on availability</li>
<li>higher than normal priority. Pieces are preferred over pieces with
the same availability, but not over pieces with lower availability</li>
<li>pieces are as likely to be picked as partial pieces.</li>
<li>pieces are preferred over partial pieces, but not over pieces with
lower availability</li>
<li><em>currently the same as 4</em></li>
<li>piece is as likely to be picked as any piece with availability 1</li>
<li>maximum priority, availability is disregarded, the piece is preferred
over any other piece with lower priority</li>
</ol>
</blockquote>
<p>The exact definitions of these priorities are implementation details, and
subject to change. The interface guarantees that higher number means higher
priority, and that 0 means do not download.</p>
<p><tt class="docutils literal">piece_priority</tt> sets or gets the priority for an individual piece,
specified by <tt class="docutils literal">index</tt>.</p>
<p><tt class="docutils literal">prioritize_pieces</tt> takes a vector of integers, one integer per piece in
the torrent. All the piece priorities will be updated with the priorities
in the vector.</p>
<p><tt class="docutils literal">piece_priorities</tt> returns a vector with one element for each piece in the
torrent. Each element is the current priority of that piece.</p>
</div>
<div class="section" id="file-priority-prioritize-files-file-priorities">
<h2>file_priority() prioritize_files() file_priorities()</h2>
<blockquote>
<pre class="literal-block">
void file_priority(int index, int priority) const;
int file_priority(int index) const;
void prioritize_files(std::vector&lt;int&gt; const&amp; files) const;
std::vector&lt;int&gt; file_priorities() const;
</pre>
</blockquote>
<p><tt class="docutils literal">index</tt> must be in the range [0, number_of_files).</p>
<p><tt class="docutils literal">file_priority</tt> queries or sets the priority of file <tt class="docutils literal">index</tt>.</p>
<p><tt class="docutils literal">prioritize_files</tt> takes a vector that has at as many elements as there are
files in the torrent. Each entry is the priority of that file. The function
sets the priorities of all the pieces in the torrent based on the vector.</p>
<p><tt class="docutils literal">file_priorities</tt> returns a vector with the priorities of all files.</p>
<p>The priority values are the same as for <tt class="docutils literal">piece_priority</tt>.</p>
<p>Whenever a file priority is changed, all other piece priorities are reset
to match the file priorities. In order to maintain sepcial priorities for
particular pieces, <tt class="docutils literal">piece_priority</tt> has to be called again for those pieces.</p>
<p>You cannot set the file priorities on a torrent that does not yet
have metadata or a torrent that is a seed. <tt class="docutils literal">file_priority(int, int)</tt> and
<tt class="docutils literal">prioritize_files()</tt> are both no-ops for such torrents.</p>
</div>
<div class="section" id="file-progress">
<h2>file_progress()</h2>
<blockquote>
<pre class="literal-block">
void file_progress(std::vector&lt;size_type&gt;&amp; fp, int flags = 0);
</pre>
</blockquote>
<p>This function fills in the supplied vector with the the number of bytes downloaded
of each file in this torrent. The progress values are ordered the same as the files
in the <a class="reference internal" href="#torrent-info">torrent_info</a>. This operation is not very cheap. Its complexity is <em>O(n + mj)</em>.
Where <em>n</em> is the number of files, <em>m</em> is the number of downloading pieces and <em>j</em>
is the number of blocks in a piece.</p>
<p>The <tt class="docutils literal">flags</tt> parameter can be used to specify the granularity of the file progress. If
left at the default value of 0, the progress will be as accurate as possible, but also
more expensive to calculate. If <tt class="docutils literal"><span class="pre">torrent_handle::piece_granularity</span></tt> is specified,
the progress will be specified in piece granularity. i.e. only pieces that have been
fully downloaded and passed the hash check count. When specifying piece granularity,
the operation is a lot cheaper, since libtorrent already keeps track of this internally
and no calculation is required.</p>
</div>
<div class="section" id="save-path">
<h2>save_path()</h2>
<blockquote>
<pre class="literal-block">
std::string save_path() const;
</pre>
</blockquote>
<p><tt class="docutils literal">save_path()</tt> returns the path that was given to <a class="reference internal" href="#async-add-torrent-add-torrent">async_add_torrent() add_torrent()</a> when this torrent
was started.</p>
</div>
<div class="section" id="move-storage">
<h2>move_storage()</h2>
<blockquote>
<pre class="literal-block">
void move_storage(std::string const&amp; save_path) const;
void move_storage(std::wstring const&amp; save_path) const;
</pre>
</blockquote>
<p>Moves the file(s) that this torrent are currently seeding from or downloading to. If
the given <tt class="docutils literal">save_path</tt> is not located on the same drive as the original save path,
The files will be copied to the new drive and removed from their original location.
This will block all other disk IO, and other torrents download and upload rates may
drop while copying the file.</p>
<p>Since disk IO is performed in a separate thread, this operation is also asynchronous.
Once the operation completes, the <tt class="docutils literal">storage_moved_alert</tt> is generated, with the new
path as the message. If the move fails for some reason, <tt class="docutils literal">storage_moved_failed_alert</tt>
is generated instead, containing the error message.</p>
</div>
<div class="section" id="id4">
<h2>rename_file()</h2>
<blockquote>
<pre class="literal-block">
void rename_file(int index, std::string) const;
void rename_file(int index, std::wstring) const;
</pre>
</blockquote>
<p>Renames the file with the given index asynchronously. The rename operation is complete
when either a <tt class="docutils literal">file_renamed_alert</tt> or <tt class="docutils literal">file_rename_failed_alert</tt> is posted.</p>
</div>
<div class="section" id="get-storage-impl">
<h2>get_storage_impl()</h2>
<blockquote>
<pre class="literal-block">
storage_interface* get_storage_impl() const;
</pre>
</blockquote>
<p>Returns the storage implementation for this torrent. This depends on the
storage contructor function that was passed to <tt class="docutils literal"><span class="pre">session::add_torrent</span></tt>.</p>
</div>
<div class="section" id="super-seeding">
<h2>super_seeding()</h2>
<blockquote>
<pre class="literal-block">
void super_seeding(bool on) const;
</pre>
</blockquote>
<p>Enables or disabled super seeding/initial seeding for this torrent. The torrent
needs to be a seed for this to take effect.</p>
</div>
<div class="section" id="add-piece">
<h2>add_piece()</h2>
<blockquote>
<pre class="literal-block">
enum flags_t { overwrite_existing = 1 };
void add_piece(int piece, char const* data, int flags = 0) const;
</pre>
</blockquote>
<p>This function will write <tt class="docutils literal">data</tt> to the storage as piece <tt class="docutils literal">piece</tt>, as if it had
been downloaded from a peer. <tt class="docutils literal">data</tt> is expected to point to a buffer of as many
bytes as the size of the specified piece. The data in the buffer is copied and
passed on to the disk IO thread to be written at a later point.</p>
<p>By default, data that's already been downloaded is not overwritten by this buffer. If
you trust this data to be correct (and pass the piece hash check) you may pass the
<tt class="docutils literal">overwrite_existing</tt> flag. This will instruct libtorrent to overwrite any data that
may already have been downloaded with this data.</p>
<p>Since the data is written asynchronously, you may know that is passed or failed the
hash check by waiting for <tt class="docutils literal">piece_finished_alert</tt> or <tt class="docutils literal">has_failed_alert</tt>.</p>
</div>
<div class="section" id="read-piece">
<h2>read_piece()</h2>
<blockquote>
<pre class="literal-block">
void read_piece(int piece) const;
</pre>
</blockquote>
<p>This function starts an asynchronous read operation of the specified piece from
this torrent. You must have completed the download of the specified piece before
calling this function.</p>
<p>When the read operation is completed, it is passed back through an alert,
<a class="reference internal" href="#read-piece-alert">read_piece_alert</a>. Since this alert is a reponse to an explicit call, it will
always be posted, regardless of the alert mask.</p>
<p>Note that if you read multiple pieces, the read operations are not guaranteed to
finish in the same order as you initiated them.</p>
</div>
<div class="section" id="have-piece">
<h2>have_piece()</h2>
<blockquote>
<pre class="literal-block">
bool have_piece(int piece) const;
</pre>
</blockquote>
<p>Returns true if this piece has been completely downloaded, and false otherwise.</p>
</div>
<div class="section" id="force-reannounce-force-dht-announce">
<h2>force_reannounce() force_dht_announce()</h2>
<blockquote>
<pre class="literal-block">
void force_reannounce() const;
void force_reannounce(boost::posix_time::time_duration) const;
void force_dht_announce() const;
</pre>
</blockquote>
<p><tt class="docutils literal">force_reannounce()</tt> will force this torrent to do another tracker request, to receive new
peers. The second overload of <tt class="docutils literal">force_reannounce</tt> that takes a <tt class="docutils literal">time_duration</tt> as
argument will schedule a reannounce in that amount of time from now.</p>
<p>If the tracker's <tt class="docutils literal">min_interval</tt> has not passed since the last announce, the forced
announce will be scheduled to happen immediately as the <tt class="docutils literal">min_interval</tt> expires. This is
to honor trackers minimum re-announce interval settings.</p>
<p><tt class="docutils literal">force_dht_announce</tt> will announce the torrent to the DHT immediately.</p>
</div>
<div class="section" id="scrape-tracker">
<h2>scrape_tracker()</h2>
<blockquote>
<pre class="literal-block">
void scrape_tracker() const;
</pre>
</blockquote>
<p><tt class="docutils literal">scrape_tracker()</tt> will send a scrape request to the tracker. A scrape request queries the
tracker for statistics such as total number of incomplete peers, complete peers, number of
downloads etc.</p>
<p>This request will specifically update the <tt class="docutils literal">num_complete</tt> and <tt class="docutils literal">num_incomplete</tt> fields in
the <a class="reference internal" href="#torrent-status">torrent_status</a> struct once it completes. When it completes, it will generate a
<a class="reference internal" href="#scrape-reply-alert">scrape_reply_alert</a>. If it fails, it will generate a <a class="reference internal" href="#scrape-failed-alert">scrape_failed_alert</a>.</p>
</div>
<div class="section" id="connect-peer">
<h2>connect_peer()</h2>
<blockquote>
<pre class="literal-block">
void connect_peer(asio::ip::tcp::endpoint const&amp; adr, int source = 0) const;
</pre>
</blockquote>
<p><tt class="docutils literal">connect_peer()</tt> is a way to manually connect to peers that one believe is a part of the
torrent. If the peer does not respond, or is not a member of this torrent, it will simply
be disconnected. No harm can be done by using this other than an unnecessary connection
attempt is made. If the torrent is uninitialized or in queued or checking mode, this
will throw <a class="reference internal" href="#libtorrent-exception">libtorrent_exception</a>. The second (optional) argument will be bitwised ORed into
the source mask of this peer. Typically this is one of the source flags in <a class="reference internal" href="#peer-info">peer_info</a>.
i.e. <tt class="docutils literal">tracker</tt>, <tt class="docutils literal">pex</tt>, <tt class="docutils literal">dht</tt> etc.</p>
</div>
<div class="section" id="name">
<h2>name()</h2>
<blockquote>
<pre class="literal-block">
std::string name() const;
</pre>
</blockquote>
<p>Returns the name of the torrent. i.e. the name from the metadata associated with it. In
case the torrent was started without metadata, and hasn't completely received it yet,
it returns the name given to it when added to the session. See <tt class="docutils literal"><span class="pre">session::add_torrent</span></tt>.</p>
</div>
<div class="section" id="set-upload-limit-set-download-limit-upload-limit-download-limit">
<h2>set_upload_limit() set_download_limit() upload_limit() download_limit()</h2>
<blockquote>
<pre class="literal-block">
void set_upload_limit(int limit) const;
void set_download_limit(int limit) const;
int upload_limit() const;
int download_limit() const;
</pre>
</blockquote>
<p><tt class="docutils literal">set_upload_limit</tt> will limit the upload bandwidth used by this particular torrent to the
limit you set. It is given as the number of bytes per second the torrent is allowed to upload.
<tt class="docutils literal">set_download_limit</tt> works the same way but for download bandwidth instead of upload bandwidth.
Note that setting a higher limit on a torrent then the global limit (<tt class="docutils literal"><span class="pre">session::set_upload_rate_limit</span></tt>)
will not override the global rate limit. The torrent can never upload more than the global rate
limit.</p>
<p><tt class="docutils literal">upload_limit</tt> and <tt class="docutils literal">download_limit</tt> will return the current limit setting, for upload and
download, respectively.</p>
</div>
<div class="section" id="set-sequential-download">
<h2>set_sequential_download()</h2>
<blockquote>
<pre class="literal-block">
void set_sequential_download(bool sd);
</pre>
</blockquote>
<p><tt class="docutils literal">set_sequential_download()</tt> enables or disables <em>sequential download</em>. When enabled, the piece
picker will pick pieces in sequence instead of rarest first.</p>
<p>Enabling sequential download will affect the piece distribution negatively in the swarm. It should be
used sparingly.</p>
</div>
<div class="section" id="pause-resume">
<h2>pause() resume()</h2>
<blockquote>
<pre class="literal-block">
enum pause_flags_t { graceful_pause = 1 };
void pause(int flags) const;
void resume() const;
</pre>
</blockquote>
<p><tt class="docutils literal">pause()</tt>, and <tt class="docutils literal">resume()</tt> will disconnect all peers and reconnect all peers respectively.
When a torrent is paused, it will however remember all share ratios to all peers and remember
all potential (not connected) peers. Torrents may be paused automatically if there is a file
error (e.g. disk full) or something similar. See <a class="reference internal" href="#file-error-alert">file_error_alert</a>.</p>
<p>To know if a torrent is paused or not, call <tt class="docutils literal"><span class="pre">torrent_handle::status()</span></tt> and inspect
<tt class="docutils literal"><span class="pre">torrent_status::paused</span></tt>.</p>
<p>The <tt class="docutils literal">flags</tt> argument to pause can be set to <tt class="docutils literal"><span class="pre">torrent_handle::graceful_pause</span></tt> which will
delay the disconnect of peers that we're still downloading outstanding requests from. The torrent
will not accept any more requests and will disconnect all idle peers. As soon as a peer is
done transferring the blocks that were requested from it, it is disconnected. This is a graceful
shut down of the torrent in the sense that no downloaded bytes are wasted.</p>
<p>torrents that are auto-managed may be automatically resumed again. It does not make sense to
pause an auto-managed torrent without making it not automanaged first. Torrents are auto-managed
by default when added to the session. For more information, see <a class="reference internal" href="#queuing">queuing</a>.</p>
</div>
<div class="section" id="flush-cache">
<h2>flush_cache()</h2>
<blockquote>
<pre class="literal-block">
void flush_cache() const;
</pre>
</blockquote>
<p>Instructs libtorrent to flush all the disk caches for this torrent and close all
file handles. This is done asynchronously and you will be notified that it's complete
through <a class="reference internal" href="#cache-flushed-alert">cache_flushed_alert</a>.</p>
<p>Note that by the time you get the alert, libtorrent may have cached more data for the
torrent, but you are guaranteed that whatever cached data libtorrent had by the time
you called <tt class="docutils literal"><span class="pre">torrent_handle::flush_cache()</span></tt> has been written to disk.</p>
</div>
<div class="section" id="force-recheck">
<h2>force_recheck()</h2>
<blockquote>
<pre class="literal-block">
void force_recheck() const;
</pre>
</blockquote>
<p><tt class="docutils literal">force_recheck</tt> puts the torrent back in a state where it assumes to have no resume data.
All peers will be disconnected and the torrent will stop announcing to the tracker. The torrent
will be added to the checking queue, and will be checked (all the files will be read and
compared to the piece hashes). Once the check is complete, the torrent will start connecting
to peers again, as normal.</p>
</div>
<div class="section" id="clear-error">
<h2>clear_error()</h2>
<blockquote>
<pre class="literal-block">
void clear_error() const;
</pre>
</blockquote>
<p>If the torrent is in an error state (i.e. <tt class="docutils literal"><span class="pre">torrent_status::error</span></tt> is non-empty), this
will clear the error and start the torrent again.</p>
</div>
<div class="section" id="set-upload-mode">
<h2>set_upload_mode()</h2>
<pre class="literal-block">
void set_upload_mode(bool m) const;
</pre>
<p>Explicitly sets the upload mode of the torrent. In upload mode, the torrent will not
request any pieces. If the torrent is auto managed, it will automatically be taken out
of upload mode periodically (see <tt class="docutils literal"><span class="pre">session_settings::optimistic_disk_retry</span></tt>). Torrents
are automatically put in upload mode whenever they encounter a disk write error.</p>
<p><tt class="docutils literal">m</tt> should be true to enter upload mode, and false to leave it.</p>
<p>To test if a torrent is in upload mode, call <tt class="docutils literal"><span class="pre">torrent_handle::status()</span></tt> and inspect
<tt class="docutils literal"><span class="pre">torrent_status::upload_mode</span></tt>.</p>
</div>
<div class="section" id="set-share-mode">
<h2>set_share_mode()</h2>
<blockquote>
<pre class="literal-block">
void set_share_mode(bool m) const;
</pre>
</blockquote>
<p>Enable or disable share mode for this torrent. When in share mode, the torrent will
not necessarily be downloaded, especially not the whole of it. Only parts that are likely
to be distributed to more than 2 other peers are downloaded, and only if the previous
prediction was correct.</p>
</div>
<div class="section" id="apply-ip-filter">
<h2>apply_ip_filter()</h2>
<pre class="literal-block">
void apply_ip_filter(bool b) const;
</pre>
<p>Set to true to apply the session global IP filter to this torrent (which is the
default). Set to false to make this torrent ignore the IP filter.</p>
</div>
<div class="section" id="resolve-countries">
<h2>resolve_countries()</h2>
<blockquote>
<pre class="literal-block">
void resolve_countries(bool r);
bool resolve_countries() const;
</pre>
</blockquote>
<p>Sets or gets the flag that derermines if countries should be resolved for the peers of this
torrent. It defaults to false. If it is set to true, the <a class="reference internal" href="#peer-info">peer_info</a> structure for the peers
in this torrent will have their <tt class="docutils literal">country</tt> member set. See <a class="reference internal" href="#peer-info">peer_info</a> for more information
on how to interpret this field.</p>
</div>
<div class="section" id="is-seed">
<h2>is_seed()</h2>
<blockquote>
<pre class="literal-block">
bool is_seed() const;
</pre>
</blockquote>
<p>Returns true if the torrent is in seed mode (i.e. if it has finished downloading).</p>
</div>
<div class="section" id="auto-managed">
<h2>auto_managed()</h2>
<blockquote>
<pre class="literal-block">
void auto_managed(bool m) const;
</pre>
</blockquote>
<p><tt class="docutils literal">auto_managed()</tt> changes whether the torrent is auto managed or not. For more info,
see <a class="reference internal" href="#queuing">queuing</a>.</p>
</div>
<div class="section" id="set-metadata">
<h2>set_metadata()</h2>
<blockquote>
<pre class="literal-block">
bool set_metadata(char const* buf, int size) const;
</pre>
</blockquote>
<p><tt class="docutils literal">set_metadata</tt> expects the <em>info</em> section of metadata. i.e. The buffer passed in will be
hashed and verified against the info-hash. If it fails, a <tt class="docutils literal">metadata_failed_alert</tt> will be
generated. If it passes, a <tt class="docutils literal">metadata_received_alert</tt> is generated. The function returns
true if the metadata is successfully set on the torrent, and false otherwise. If the torrent
already has metadata, this function will not affect the torrent, and false will be returned.</p>
</div>
<div class="section" id="set-tracker-login">
<h2>set_tracker_login()</h2>
<blockquote>
<pre class="literal-block">
void set_tracker_login(std::string const&amp; username
        , std::string const&amp; password) const;
</pre>
</blockquote>
<p><tt class="docutils literal">set_tracker_login()</tt> sets a username and password that will be sent along in the HTTP-request
of the tracker announce. Set this if the tracker requires authorization.</p>
</div>
<div class="section" id="trackers-replace-trackers-add-tracker">
<h2>trackers() replace_trackers() add_tracker()</h2>
<blockquote>
<pre class="literal-block">
std::vector&lt;announce_entry&gt; trackers() const;
void replace_trackers(std::vector&lt;announce_entry&gt; const&amp;) const;
void add_tracker(announc_entry const&amp; url);
</pre>
</blockquote>
<p><tt class="docutils literal">trackers()</tt> will return the list of trackers for this torrent. The
announce entry contains both a string <tt class="docutils literal">url</tt> which specify the announce url
for the tracker as well as an int <tt class="docutils literal">tier</tt>, which is specifies the order in
which this tracker is tried. If you want libtorrent to use another list of
trackers for this torrent, you can use <tt class="docutils literal">replace_trackers()</tt> which takes
a list of the same form as the one returned from <tt class="docutils literal">trackers()</tt> and will
replace it. If you want an immediate effect, you have to call
<a class="reference internal" href="#force-reannounce-force-dht-announce">force_reannounce() force_dht_announce()</a>. See <a class="reference internal" href="#trackers">trackers()</a> for the definition of <tt class="docutils literal">announce_entry</tt>.</p>
<p><tt class="docutils literal">add_tracker()</tt> will look if the specified tracker is already in the set.
If it is, it doesn't do anything. If it's not in the current set of trackers,
it will insert it in the tier specified in the announce_entry.</p>
<p>The updated set of trackers will be saved in the resume data, and when a torrent
is started with resume data, the trackers from the resume data will replace the
original ones.</p>
</div>
<div class="section" id="add-url-seed-remove-url-seed-url-seeds">
<h2>add_url_seed() remove_url_seed() url_seeds()</h2>
<blockquote>
<pre class="literal-block">
void add_url_seed(std::string const&amp; url);
void remove_url_seed(std::string const&amp; url);
std::set&lt;std::string&gt; url_seeds() const;
</pre>
</blockquote>
<p><tt class="docutils literal">add_url_seed()</tt> adds another url to the torrent's list of url seeds. If the
given url already exists in that list, the call has no effect. The torrent
will connect to the server and try to download pieces from it, unless it's
paused, queued, checking or seeding. <tt class="docutils literal">remove_url_seed()</tt> removes the given
url if it exists already. <tt class="docutils literal">url_seeds()</tt> return a set of the url seeds
currently in this torrent. Note that urls that fails may be removed
automatically from the list.</p>
<p>See <a class="reference internal" href="#http-seeding">HTTP seeding</a> for more information.</p>
</div>
<div class="section" id="add-http-seed-remove-http-seed-http-seeds">
<h2>add_http_seed() remove_http_seed() http_seeds()</h2>
<blockquote>
<pre class="literal-block">
void add_http_seed(std::string const&amp; url);
void remove_http_seed(std::string const&amp; url);
std::set&lt;std::string&gt; http_seeds() const;
</pre>
</blockquote>
<p>These functions are identical as the <tt class="docutils literal">*_url_seed()</tt> variants, but they
operate on BEP 17 web seeds instead of BEP 19.</p>
<p>See <a class="reference internal" href="#http-seeding">HTTP seeding</a> for more information.</p>
</div>
<div class="section" id="queue-position-queue-position-up-queue-position-down-queue-position-top-queue-position-bottom">
<h2>queue_position() queue_position_up() queue_position_down() queue_position_top() queue_position_bottom()</h2>
<blockquote>
<pre class="literal-block">
int queue_position() const;
void queue_position_up() const;
void queue_position_down() const;
void queue_position_top() const;
void queue_position_bottom() const;
</pre>
</blockquote>
<p>Every torrent that is added is assigned a queue position exactly one greater than
the greatest queue position of all existing torrents. Torrents that are being
seeded have -1 as their queue position, since they're no longer in line to be downloaded.</p>
<p>When a torrent is removed or turns into a seed, all torrents with greater queue positions
have their positions decreased to fill in the space in the sequence.</p>
<p><tt class="docutils literal">queue_position()</tt> returns the torrent's position in the download queue. The torrents
with the smallest numbers are the ones that are being downloaded. The smaller number,
the closer the torrent is to the front of the line to be started.</p>
<p>The queue position is also available in the <tt class="docutils literal">torrent_status</tt>.</p>
<p>The <tt class="docutils literal"><span class="pre">queue_position_*()</span></tt> functions adjust the torrents position in the queue. Up means
closer to the front and down means closer to the back of the queue. Top and bottom refers
to the front and the back of the queue respectively.</p>
</div>
<div class="section" id="set-priority">
<h2>set_priority()</h2>
<blockquote>
<pre class="literal-block">
void set_priority(int prio) const;
</pre>
</blockquote>
<p>This sets the bandwidth priority of this torrent. The priority of a torrent determines
how much bandwidth its peers are assigned when distributing upload and download rate quotas.
A high number gives more bandwidth. The priority must be within the range [0, 255].</p>
<p>The default priority is 0, which is the lowest priority.</p>
<p>To query the priority of a torrent, use the <tt class="docutils literal"><span class="pre">torrent_handle::status()</span></tt> call.</p>
<p>Torrents with higher priority will not nececcarily get as much bandwidth as they can
consume, even if there's is more quota. Other peers will still be weighed in when
bandwidth is being distributed. With other words, bandwidth is not distributed strictly
in order of priority, but the priority is used as a weight.</p>
<p>Peers whose Torrent has a higher priority will take precedence when distributing unchoke slots.
This is a strict prioritization where every interested peer on a high priority torrent will
be unchoked before any other, lower priority, torrents have any peers unchoked.</p>
</div>
<div class="section" id="use-interface">
<h2>use_interface()</h2>
<blockquote>
<pre class="literal-block">
void use_interface(char const* net_interface) const;
</pre>
</blockquote>
<p><tt class="docutils literal">use_interface()</tt> sets the network interface this torrent will use when it opens outgoing
connections. By default, it uses the same interface as the <a class="reference internal" href="#session">session</a> uses to listen on. The
parameter must be a string containing one or more, comma separated, ip-address (either an
IPv4 or IPv6 address). When specifying multiple interfaces, the torrent will round-robin
which interface to use for each outgoing conneciton. This is useful for clients that are
multi-homed.</p>
</div>
<div class="section" id="info-hash">
<h2>info_hash()</h2>
<blockquote>
<pre class="literal-block">
sha1_hash info_hash() const;
</pre>
</blockquote>
<p><tt class="docutils literal">info_hash()</tt> returns the info-hash for the torrent.</p>
</div>
<div class="section" id="set-max-uploads-max-uploads">
<h2>set_max_uploads() max_uploads()</h2>
<blockquote>
<pre class="literal-block">
void set_max_uploads(int max_uploads) const;
int max_uploads() const;
</pre>
</blockquote>
<p><tt class="docutils literal">set_max_uploads()</tt> sets the maximum number of peers that's unchoked at the same time on this
torrent. If you set this to -1, there will be no limit.</p>
<p><tt class="docutils literal">max_uploads()</tt> returns the current settings.</p>
</div>
<div class="section" id="set-max-connections-max-connections">
<h2>set_max_connections() max_connections()</h2>
<blockquote>
<pre class="literal-block">
void set_max_connections(int max_connections) const;
int max_connections() const;
</pre>
</blockquote>
<p><tt class="docutils literal">set_max_connections()</tt> sets the maximum number of connection this torrent will open. If all
connections are used up, incoming connections may be refused or poor connections may be closed.
This must be at least 2. The default is unlimited number of connections. If -1 is given to the
function, it means unlimited.</p>
<p><tt class="docutils literal">max_connections()</tt> returns the current settings.</p>
</div>
<div class="section" id="save-resume-data">
<h2>save_resume_data()</h2>
<blockquote>
<pre class="literal-block">
enum save_resume_flags_t { flush_disk_cache = 1, save_info_dict = 2 };
void save_resume_data(int flags = 0) const;
</pre>
</blockquote>
<p><tt class="docutils literal">save_resume_data()</tt> generates fast-resume data and returns it as an <a class="reference internal" href="#entry">entry</a>. This <a class="reference internal" href="#entry">entry</a>
is suitable for being bencoded. For more information about how fast-resume works, see <a class="reference internal" href="#fast-resume">fast resume</a>.</p>
<p>The <tt class="docutils literal">flags</tt> argument is a bitmask of flags ORed together. If the flag <tt class="docutils literal"><span class="pre">torrent_handle::flush_cache</span></tt>
is set, the disk cache will be flushed before creating the resume data. This avoids a problem with
file timestamps in the resume data in case the cache hasn't been flushed yet.</p>
<p>If the flag <tt class="docutils literal"><span class="pre">torrent_handle::save_info_dict</span></tt> is set, the resume data will contain the metadata
from the torrent file as well. This is default for any torrent that's added without a torrent
file (such as a magnet link or a URL).</p>
<p>This operation is asynchronous, <tt class="docutils literal">save_resume_data</tt> will return immediately. The resume data
is delivered when it's done through an <a class="reference internal" href="#save-resume-data-alert">save_resume_data_alert</a>.</p>
<p>The fast resume data will be empty in the following cases:</p>
<blockquote>
<ol class="arabic simple">
<li>The torrent handle is invalid.</li>
<li>The torrent is checking (or is queued for checking) its storage, it will obviously
not be ready to write resume data.</li>
<li>The torrent hasn't received valid metadata and was started without metadata
(see libtorrent's <a class="reference internal" href="#metadata-from-peers">metadata from peers</a> extension)</li>
</ol>
</blockquote>
<p>Note that by the time you receive the fast resume data, it may already be invalid if the torrent
is still downloading! The recommended practice is to first pause the session, then generate the
fast resume data, and then close it down. Make sure to not <a class="reference internal" href="#remove-torrent">remove_torrent()</a> before you receive
the <a class="reference internal" href="#save-resume-data-alert">save_resume_data_alert</a> though. There's no need to pause when saving intermittent resume data.</p>
<div class="warning">
<p class="first admonition-title">Warning</p>
<p class="last">If you pause every torrent individually instead of pausing the session, every torrent
will have its paused state saved in the resume data!</p>
</div>
<div class="warning">
<p class="first admonition-title">Warning</p>
<p class="last">The resume data contains the modification timestamps for all files. If one file has
been modified when the torrent is added again, the will be rechecked. When shutting down, make
sure to flush the disk cache before saving the resume data. This will make sure that the file
timestamps are up to date and won't be modified after saving the resume data. The recommended way
to do this is to pause the torrent, which will flush the cache and disconnect all peers.</p>
</div>
<div class="note">
<p class="first admonition-title">Note</p>
<p>It is typically a good idea to save resume data whenever a torrent is completed or paused. In those
cases you don't need to pause the torrent or the session, since the torrent will do no more writing
to its files. If you save resume data for torrents when they are paused, you can accelerate the
shutdown process by not saving resume data again for paused torrents. Completed torrents should
have their resume data saved when they complete and on exit, since their statistics might be updated.</p>
<p class="last">In full allocation mode the reume data is never invalidated by subsequent
writes to the files, since pieces won't move around. This means that you don't need to
pause before writing resume data in full or sparse mode. If you don't, however, any data written to
disk after you saved resume data and before the <a class="reference internal" href="#session">session</a> closed is lost.</p>
</div>
<p>It also means that if the resume data is out dated, libtorrent will not re-check the files, but assume
that it is fairly recent. The assumption is that it's better to loose a little bit than to re-check
the entire file.</p>
<p>It is still a good idea to save resume data periodically during download as well as when
closing down.</p>
<p>Example code to pause and save resume data for all torrents and wait for the alerts:</p>
<pre class="literal-block">
extern int outstanding_resume_data; // global counter of outstanding resume data
std::vector&lt;torrent_handle&gt; handles = ses.get_torrents();
ses.pause();
for (std::vector&lt;torrent_handle&gt;::iterator i = handles.begin();
        i != handles.end(); ++i)
{
        torrent_handle&amp; h = *i;
        if (!h.is_valid()) continue;
        torrent_status s = h.status();
        if (!s.has_metadata) continue;
        if (!s.need_save_resume_data()) continue;

        h.save_resume_data();
        ++outstanding_resume_data;
}

while (outstanding_resume_data &gt; 0)
{
        alert const* a = ses.wait_for_alert(seconds(10));

        // if we don't get an alert within 10 seconds, abort
        if (a == 0) break;

        std::auto_ptr&lt;alert&gt; holder = ses.pop_alert();

        if (alert_cast&lt;save_resume_data_failed_alert&gt;(a))
        {
                process_alert(a);
                --outstanding_resume_data;
                continue;
        }

        save_resume_data_alert const* rd = alert_cast&lt;save_resume_data_alert&gt;(a);
        if (rd == 0)
        {
                process_alert(a);
                continue;
        }

        torrent_handle h = rd-&gt;handle;
        std::ofstream out((h.save_path() + &quot;/&quot; + h.torrent_file()-&gt;name() + &quot;.fastresume&quot;).c_str()
                , std::ios_base::binary);
        out.unsetf(std::ios_base::skipws);
        bencode(std::ostream_iterator&lt;char&gt;(out), *rd-&gt;resume_data);
        --outstanding_resume_data;
}
</pre>
<div class="note">
<p class="first admonition-title">Note</p>
<p class="last">Note how <tt class="docutils literal">outstanding_resume_data</tt> is a global counter in this example.
This is deliberate, otherwise there is a race condition for torrents that
was just asked to save their resume data, they posted the alert, but it has
not been received yet. Those torrents would report that they don't need to
save resume data again, and skipped by the initial loop, and thwart the counter
otherwise.</p>
</div>
</div>
<div class="section" id="need-save-resume-data">
<h2>need_save_resume_data()</h2>
<blockquote>
<pre class="literal-block">
bool need_save_resume_data() const;
</pre>
</blockquote>
<p>This function returns true if any whole chunk has been downloaded since the
torrent was first loaded or since the last time the resume data was saved. When
saving resume data periodically, it makes sense to skip any torrent which hasn't
downloaded anything since the last time.</p>
<div class="note">
<p class="first admonition-title">Note</p>
<p class="last">A torrent's resume data is considered saved as soon as the alert
is posted. It is important to make sure this alert is received and handled
in order for this function to be meaningful.</p>
</div>
</div>
<div class="section" id="id5">
<h2>status()</h2>
<blockquote>
<pre class="literal-block">
torrent_status status(boost::uint32_t flags = 0xffffffff) const;
</pre>
</blockquote>
<p><tt class="docutils literal">status()</tt> will return a structure with information about the status of this
torrent. If the <a class="reference internal" href="#torrent-handle">torrent_handle</a> is invalid, it will throw <a class="reference internal" href="#libtorrent-exception">libtorrent_exception</a> exception.
See <a class="reference internal" href="#torrent-status">torrent_status</a>. The <tt class="docutils literal">flags</tt> argument filters what information is returned
in the torrent_status. Some information in there is relatively expensive to calculate, and
if you're not interested in it (and see performance issues), you can filter them out.</p>
<p>By default everything is included. The flags you can use to decide what to <em>include</em> are:</p>
<ul>
<li><dl class="first docutils">
<dt><tt class="docutils literal">query_distributed_copies</tt></dt>
<dd><p class="first last">calculates <tt class="docutils literal">distributed_copies</tt>, <tt class="docutils literal">distributed_full_copies</tt> and <tt class="docutils literal">distributed_fraction</tt>.</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><tt class="docutils literal">query_accurate_download_counters</tt></dt>
<dd><p class="first last">includes partial downloaded blocks in <tt class="docutils literal">total_done</tt> and <tt class="docutils literal">total_wanted_done</tt>.</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><tt class="docutils literal">query_last_seen_complete</tt></dt>
<dd><p class="first last">includes <tt class="docutils literal">last_seen_complete</tt>.</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><tt class="docutils literal">query_pieces</tt></dt>
<dd><p class="first last">includes <tt class="docutils literal">pieces</tt>.</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><tt class="docutils literal">query_verified_pieces</tt></dt>
<dd><p class="first last">includes <tt class="docutils literal">verified_pieces</tt> (only applies to torrents in <em>seed mode</em>).</p>
</dd>
</dl>
</li>
</ul>
</div>
<div class="section" id="get-download-queue">
<h2>get_download_queue()</h2>
<blockquote>
<pre class="literal-block">
void get_download_queue(std::vector&lt;partial_piece_info&gt;&amp; queue) const;
</pre>
</blockquote>
<p><tt class="docutils literal">get_download_queue()</tt> takes a non-const reference to a vector which it will fill with
information about pieces that are partially downloaded or not downloaded at all but partially
requested. The entry in the vector (<tt class="docutils literal">partial_piece_info</tt>) looks like this:</p>
<pre class="literal-block">
struct partial_piece_info
{
        int piece_index;
        int blocks_in_piece;
        enum state_t { none, slow, medium, fast };
        state_t piece_state;
        block_info* blocks;
};
</pre>
<p><tt class="docutils literal">piece_index</tt> is the index of the piece in question. <tt class="docutils literal">blocks_in_piece</tt> is the
number of blocks in this particular piece. This number will be the same for most pieces, but
the last piece may have fewer blocks than the standard pieces.</p>
<p><tt class="docutils literal">piece_state</tt> is set to either <tt class="docutils literal">fast</tt>, <tt class="docutils literal">medium</tt>, <tt class="docutils literal">slow</tt> or <tt class="docutils literal">none</tt>. It tells which
download rate category the peers downloading this piece falls into. <tt class="docutils literal">none</tt> means that no
peer is currently downloading any part of the piece. Peers prefer picking pieces from
the same category as themselves. The reason for this is to keep the number of partially
downloaded pieces down. Pieces set to <tt class="docutils literal">none</tt> can be converted into any of <tt class="docutils literal">fast</tt>,
<tt class="docutils literal">medium</tt> or <tt class="docutils literal">slow</tt> as soon as a peer want to download from it.</p>
<pre class="literal-block">
struct block_info
{
        enum block_state_t
        { none, requested, writing, finished };

        void set_peer(tcp::endpoint const&amp; ep);
        tcp::endpoint peer() const;

        unsigned bytes_progress:15;
        unsigned block_size:15;
        unsigned state:2;
        unsigned num_peers:14;
};
</pre>
<p>The <tt class="docutils literal">blocks</tt> field points to an array of <tt class="docutils literal">blocks_in_piece</tt> elements. This pointer is
only valid until the next call to <tt class="docutils literal">get_download_queue()</tt> for any torrent in the same session.
They all share the storaga for the block arrays in their session object.</p>
<p>The <tt class="docutils literal">block_info</tt> array contains data for each individual block in the piece. Each block has
a state (<tt class="docutils literal">state</tt>) which is any of:</p>
<ul class="simple">
<li><tt class="docutils literal">none</tt> - This block has not been downloaded or requested form any peer.</li>
<li><tt class="docutils literal">requested</tt> - The block has been requested, but not completely downloaded yet.</li>
<li><tt class="docutils literal">writing</tt> - The block has been downloaded and is currently queued for being written to disk.</li>
<li><tt class="docutils literal">finished</tt> - The block has been written to disk.</li>
</ul>
<p>The <tt class="docutils literal">peer</tt> field is the ip address of the peer this block was downloaded from.
<tt class="docutils literal">num_peers</tt> is the number of peers that is currently requesting this block. Typically this
is 0 or 1, but at the end of the torrent blocks may be requested by more peers in parallel to
speed things up.
<tt class="docutils literal">bytes_progress</tt> is the number of bytes that have been received for this block, and
<tt class="docutils literal">block_size</tt> is the total number of bytes in this block.</p>
</div>
<div class="section" id="get-peer-info">
<h2>get_peer_info()</h2>
<blockquote>
<pre class="literal-block">
void get_peer_info(std::vector&lt;peer_info&gt;&amp;) const;
</pre>
</blockquote>
<p><tt class="docutils literal">get_peer_info()</tt> takes a reference to a vector that will be cleared and filled
with one entry for each peer connected to this torrent, given the handle is valid. If the
<a class="reference internal" href="#torrent-handle">torrent_handle</a> is invalid, it will throw <a class="reference internal" href="#libtorrent-exception">libtorrent_exception</a> exception. Each entry in
the vector contains information about that particular peer. See <a class="reference internal" href="#peer-info">peer_info</a>.</p>
</div>
<div class="section" id="torrent-file">
<h2>torrent_file()</h2>
<blockquote>
<pre class="literal-block">
boost::intrusive_ptr&lt;torrent_info&gt; torrent_file() const;
</pre>
</blockquote>
<p>Returns a pointer to the <a class="reference internal" href="#torrent-info">torrent_info</a> object associated with this torrent. The
<tt class="docutils literal">torrent_info</tt> object is a copy of the internal object. If the torrent doesn't
have metadata, the object being returned will not be fully filled in.
The torrent may be in a state without metadata only if
it was started without a .torrent file, e.g. by using the libtorrent extension of
just supplying a tracker and info-hash.</p>
</div>
<div class="section" id="is-valid">
<h2>is_valid()</h2>
<blockquote>
<pre class="literal-block">
bool is_valid() const;
</pre>
</blockquote>
<p>Returns true if this handle refers to a valid torrent and false if it hasn't been initialized
or if the torrent it refers to has been aborted. Note that a handle may become invalid after
it has been added to the session. Usually this is because the storage for the torrent is
somehow invalid or if the filenames are not allowed (and hence cannot be opened/created) on
your filesystem. If such an error occurs, a <a class="reference internal" href="#file-error-alert">file_error_alert</a> is generated and all handles
that refers to that torrent will become invalid.</p>
</div>
<div class="section" id="set-ssl-certificate">
<h2>set_ssl_certificate()</h2>
<blockquote>
<pre class="literal-block">
void set_ssl_certificate(std::string const&amp; cert, std::string const&amp; private_key
        , std::string const&amp; dh_params, std::string const&amp; passphrase = &quot;&quot;);
</pre>
</blockquote>
<p>For SSL torrents, use this to specify a path to a .pem file to use as this client's certificate.
The certificate must be signed by the certificate in the .torrent file to be valid.</p>
<p><tt class="docutils literal">cert</tt> is a path to the (signed) certificate in .pem format corresponding to this torrent.</p>
<p><tt class="docutils literal">private_key</tt> is a path to the private key for the specified certificate. This must be in .pem
format.</p>
<p><tt class="docutils literal">dh_params</tt> is a path to the Diffie-Hellman parameter file, which needs to be in .pem format.
You can generate this file using the openssl command like this:
<tt class="docutils literal">openssl dhparam <span class="pre">-outform</span> PEM <span class="pre">-out</span> dhparams.pem 512</tt>.</p>
<p><tt class="docutils literal">passphrase</tt> may be specified if the private key is encrypted and requires a passphrase to
be decrypted.</p>
<p>Note that when a torrent first starts up, and it needs a certificate, it will suspend connecting
to any peers until it has one. It's typically desirable to resume the torrent after setting the
ssl certificate.</p>
<p>If you receive a <a class="reference internal" href="#torrent-need-cert-alert">torrent_need_cert_alert</a>, you need to call this to provide a valid cert. If you
don't have a cert you won't be allowed to connect to any peers.</p>
</div>
<div class="section" id="native-handle">
<h2>native_handle()</h2>
<blockquote>
<pre class="literal-block">
boost::shared_ptr&lt;torrent&gt; native_handle() const;
</pre>
</blockquote>
<p>This function is intended only for use by plugins and the alert dispatch function. Any code
that runs in libtorrent's network thread may not use the public API of <tt class="docutils literal">torrent_handle</tt>.
Doing so results in a dead-lock. For such routines, the <tt class="docutils literal">native_handle</tt> gives access to the
underlying type representing the torrent. This type does not have a stable API and should
be relied on as little as possible.</p>
</div>
</div>
<div class="section" id="torrent-status">
<h1>torrent_status</h1>
<p>It contains the following fields:</p>
<pre class="literal-block">
struct torrent_status
{
        enum state_t
        {
                queued_for_checking,
                checking_files,
                downloading_metadata,
                downloading,
                finished,
                seeding,
                allocating,
                checking_resume_data
        };

        torrent_handle handle;

        state_t state;
        bool paused;
        bool auto_managed;
        bool sequential_download;
        bool seeding;
        bool finished;
        float progress;
        int progress_ppm;
        std::string error;

        boost::posix_time::time_duration next_announce;
        boost::posix_time::time_duration announce_interval;

        std::string current_tracker;

        size_type total_download;
        size_type total_upload;

        size_type total_payload_download;
        size_type total_payload_upload;

        size_type total_failed_bytes;
        size_type total_redundant_bytes;

        int download_rate;
        int upload_rate;

        int download_payload_rate;
        int upload_payload_rate;

        int num_peers;

        int num_complete;
        int num_incomplete;

        int list_seeds;
        int list_peers;

        int connect_candidates;

        bitfield pieces;
        bitfield verified_pieces;

        int num_pieces;

        size_type total_done;
        size_type total_wanted_done;
        size_type total_wanted;

        int num_seeds;

        int distributed_full_copies;
        int distributed_fraction;

        float distributed_copies;

        int block_size;

        int num_uploads;
        int num_connections;
        int uploads_limit;
        int connections_limit;

        storage_mode_t storage_mode;

        int up_bandwidth_queue;
        int down_bandwidth_queue;

        size_type all_time_upload;
        size_type all_time_download;

        int active_time;
        int finished_time;
        int seeding_time;

        int seed_rank;

        int last_scrape;

        bool has_incoming;

        int sparse_regions;

        bool seed_mode;
        bool upload_mode;
        bool share_mode;
        bool super_seeding;

        int priority;

        time_t added_time;
        time_t completed_time;
        time_t last_seen_complete;

        int time_since_upload;
        int time_since_download;

        int queue_position;
        bool need_save_resume;
        bool ip_filter_applies;

        sha1_hash info_hash;

        int listen_port;
};
</pre>
<p><tt class="docutils literal">handle</tt> is a handle to the torrent whose status the object represents.</p>
<p><tt class="docutils literal">progress</tt> is a value in the range [0, 1], that represents the progress of the
torrent's current task. It may be checking files or downloading.</p>
<p><tt class="docutils literal">progress_ppm</tt> reflects the same value as <tt class="docutils literal">progress</tt>, but instead in a range
[0, 1000000] (ppm = parts per million). When floating point operations are disabled,
this is the only alternative to the floating point value in <tt class="docutils literal">progress</tt>.</p>
<p>The torrent's current task is in the <tt class="docutils literal">state</tt> member, it will be one of the following:</p>
<table border="1" class="docutils">
<colgroup>
<col width="31%" />
<col width="69%" />
</colgroup>
<tbody valign="top">
<tr><td><tt class="docutils literal">checking_resume_data</tt></td>
<td>The torrent is currently checking the fastresume data and
comparing it to the files on disk. This is typically
completed in a fraction of a second, but if you add a
large number of torrents at once, they will queue up.</td>
</tr>
<tr><td><tt class="docutils literal">queued_for_checking</tt></td>
<td>The torrent is in the queue for being checked. But there
currently is another torrent that are being checked.
This torrent will wait for its turn.</td>
</tr>
<tr><td><tt class="docutils literal">checking_files</tt></td>
<td>The torrent has not started its download yet, and is
currently checking existing files.</td>
</tr>
<tr><td><tt class="docutils literal">downloading_metadata</tt></td>
<td>The torrent is trying to download metadata from peers.
This assumes the metadata_transfer extension is in use.</td>
</tr>
<tr><td><tt class="docutils literal">downloading</tt></td>
<td>The torrent is being downloaded. This is the state
most torrents will be in most of the time. The progress
meter will tell how much of the files that has been
downloaded.</td>
</tr>
<tr><td><tt class="docutils literal">finished</tt></td>
<td>In this state the torrent has finished downloading but
still doesn't have the entire torrent. i.e. some pieces
are filtered and won't get downloaded.</td>
</tr>
<tr><td><tt class="docutils literal">seeding</tt></td>
<td>In this state the torrent has finished downloading and
is a pure seeder.</td>
</tr>
<tr><td><tt class="docutils literal">allocating</tt></td>
<td>If the torrent was started in full allocation mode, this
indicates that the (disk) storage for the torrent is
allocated.</td>
</tr>
</tbody>
</table>
<p>When downloading, the progress is <tt class="docutils literal">total_wanted_done</tt> / <tt class="docutils literal">total_wanted</tt>. This takes
into account files whose priority have been set to 0. They are not considered.</p>
<p><tt class="docutils literal">paused</tt> is set to true if the torrent is paused and false otherwise. It's only true
if the torrent itself is paused. If the torrent is not running because the session is
paused, this is still false. To know if a torrent is active or not, you need to inspect
both <tt class="docutils literal"><span class="pre">torrent_status::paused</span></tt> and <tt class="docutils literal"><span class="pre">session::is_paused()</span></tt>.</p>
<p><tt class="docutils literal">auto_managed</tt> is set to true if the torrent is auto managed, i.e. libtorrent is
responsible for determining whether it should be started or queued. For more info
see <a class="reference internal" href="#queuing">queuing</a></p>
<p><tt class="docutils literal">sequential_download</tt> is true when the torrent is in sequential download mode. In
this mode pieces are downloaded in order rather than rarest first.</p>
<p><tt class="docutils literal">is_seeding</tt> is true if all pieces have been downloaded.</p>
<p><tt class="docutils literal">is_finished</tt> is true if all pieces that have a priority &gt; 0 are downloaded. There is
only a distinction between finished and seeding if some pieces or files have been
set to priority 0, i.e. are not downloaded.</p>
<p><tt class="docutils literal">has_metadata</tt> is true if this torrent has metadata (either it was started from a
.torrent file or the metadata has been downloaded). The only scenario where this can be
false is when the torrent was started torrent-less (i.e. with just an info-hash and tracker
ip, a magnet link for instance).</p>
<p><tt class="docutils literal">error</tt> may be set to an error message describing why the torrent was paused, in
case it was paused by an error. If the torrent is not paused or if it's paused but
not because of an error, this string is empty.</p>
<p><tt class="docutils literal">next_announce</tt> is the time until the torrent will announce itself to the tracker. And
<tt class="docutils literal">announce_interval</tt> is the time the tracker want us to wait until we announce ourself
again the next time.</p>
<p><tt class="docutils literal">current_tracker</tt> is the URL of the last working tracker. If no tracker request has
been successful yet, it's set to an empty string.</p>
<p><tt class="docutils literal">total_download</tt> and <tt class="docutils literal">total_upload</tt> is the number of bytes downloaded and
uploaded to all peers, accumulated, <em>this session</em> only. The session is considered
to restart when a torrent is paused and restarted again. When a torrent is paused,
these counters are reset to 0. If you want complete, persistent, stats, see
<tt class="docutils literal">all_time_upload</tt> and <tt class="docutils literal">all_time_download</tt>.</p>
<p><tt class="docutils literal">total_payload_download</tt> and <tt class="docutils literal">total_payload_upload</tt> counts the amount of bytes
send and received this session, but only the actual payload data (i.e the interesting
data), these counters ignore any protocol overhead.</p>
<p><tt class="docutils literal">total_failed_bytes</tt> is the number of bytes that has been downloaded and that
has failed the piece hash test. In other words, this is just how much crap that
has been downloaded.</p>
<p><tt class="docutils literal">total_redundant_bytes</tt> is the number of bytes that has been downloaded even
though that data already was downloaded. The reason for this is that in some
situations the same data can be downloaded by mistake. When libtorrent sends
requests to a peer, and the peer doesn't send a response within a certain
timeout, libtorrent will re-request that block. Another situation when
libtorrent may re-request blocks is when the requests it sends out are not
replied in FIFO-order (it will re-request blocks that are skipped by an out of
order block). This is supposed to be as low as possible.</p>
<p><tt class="docutils literal">pieces</tt> is the bitmask that represents which pieces we have (set to true) and
the pieces we don't have. It's a pointer and may be set to 0 if the torrent isn't
downloading or seeding.</p>
<p><tt class="docutils literal">verified_pieces</tt> is a bitmask representing which pieces has had their hash
checked. This only applies to torrents in <em>seed mode</em>. If the torrent is not
in seed mode, this bitmask may be empty.</p>
<p><tt class="docutils literal">num_pieces</tt> is the number of pieces that has been downloaded. It is equivalent
to: <tt class="docutils literal"><span class="pre">std::accumulate(pieces-&gt;begin(),</span> <span class="pre">pieces-&gt;end())</span></tt>. So you don't have to
count yourself. This can be used to see if anything has updated since last time
if you want to keep a graph of the pieces up to date.</p>
<p><tt class="docutils literal">download_rate</tt> and <tt class="docutils literal">upload_rate</tt> are the total rates for all peers for this
torrent. These will usually have better precision than summing the rates from
all peers. The rates are given as the number of bytes per second. The
<tt class="docutils literal">download_payload_rate</tt> and <tt class="docutils literal">upload_payload_rate</tt> respectively is the
total transfer rate of payload only, not counting protocol chatter. This might
be slightly smaller than the other rates, but if projected over a long time
(e.g. when calculating ETA:s) the difference may be noticeable.</p>
<p><tt class="docutils literal">num_peers</tt> is the number of peers this torrent currently is connected to.
Peer connections that are in the half-open state (is attempting to connect)
or are queued for later connection attempt do not count. Although they are
visible in the peer list when you call <a class="reference internal" href="#get-peer-info">get_peer_info()</a>.</p>
<p><tt class="docutils literal">num_complete</tt> and <tt class="docutils literal">num_incomplete</tt> are set to -1 if the tracker did not
send any scrape data in its announce reply. This data is optional and may
not be available from all trackers. If these are not -1, they are the total
number of peers that are seeding (complete) and the total number of peers
that are still downloading (incomplete) this torrent.</p>
<p><tt class="docutils literal">list_seeds</tt> and <tt class="docutils literal">list_peers</tt> are the number of seeds in our peer list
and the total number of peers (including seeds) respectively. We are not
necessarily connected to all the peers in our peer list. This is the number
of peers we know of in total, including banned peers and peers that we have
failed to connect to.</p>
<p><tt class="docutils literal">connect_candidates</tt> is the number of peers in this torrent's peer list
that is a candidate to be connected to. i.e. It has fewer connect attempts
than the max fail count, it is not a seed if we are a seed, it is not banned
etc. If this is 0, it means we don't know of any more peers that we can try.</p>
<p><tt class="docutils literal">total_done</tt> is the total number of bytes of the file(s) that we have. All
this does not necessarily has to be downloaded during this session (that's
<tt class="docutils literal">total_payload_download</tt>).</p>
<p><tt class="docutils literal">total_wanted_done</tt> is the number of bytes we have downloaded, only counting the
pieces that we actually want to download. i.e. excluding any pieces that we have but
have priority 0 (i.e. not wanted).</p>
<p><tt class="docutils literal">total_wanted</tt> is the total number of bytes we want to download. This is also
excluding pieces whose priorities have been set to 0.</p>
<p><tt class="docutils literal">num_seeds</tt> is the number of peers that are seeding that this client is
currently connected to.</p>
<p><tt class="docutils literal">distributed_full_copies</tt> is the number of distributed copies of the torrent.
Note that one copy may be spread out among many peers. It tells how many copies
there are currently of the rarest piece(s) among the peers this client is
connected to.</p>
<p><tt class="docutils literal">distributed_fraction</tt> tells the share of pieces that have more copies than
the rarest piece(s). Divide this number by 1000 to get the fraction.</p>
<p>For example, if <tt class="docutils literal">distributed_full_copies</tt> is 2 and <tt class="docutils literal">distrbuted_fraction</tt>
is 500, it means that the rarest pieces have only 2 copies among the peers
this torrent is connected to, and that 50% of all the pieces have more than
two copies.</p>
<p>If we are a seed, the piece picker is deallocated as an optimization, and
piece availability is no longer tracked. In this case the distributed
copies members are set to -1.</p>
<p><tt class="docutils literal">distributed_copies</tt> is a floating point representation of the
<tt class="docutils literal">distributed_full_copies</tt> as the integer part and <tt class="docutils literal">distributed_fraction</tt>
/ 1000 as the fraction part. If floating point operations are disabled
this value is always -1.</p>
<p><tt class="docutils literal">block_size</tt> is the size of a block, in bytes. A block is a sub piece, it
is the number of bytes that each piece request asks for and the number of
bytes that each bit in the <tt class="docutils literal">partial_piece_info</tt>'s bitset represents
(see <a class="reference internal" href="#get-download-queue">get_download_queue()</a>). This is typically 16 kB, but it may be
larger if the pieces are larger.</p>
<p><tt class="docutils literal">num_uploads</tt> is the number of unchoked peers in this torrent.</p>
<p><tt class="docutils literal">num_connections</tt> is the number of peer connections this torrent has, including
half-open connections that hasn't completed the bittorrent handshake yet. This is
always &gt;= <tt class="docutils literal">num_peers</tt>.</p>
<p><tt class="docutils literal">uploads_limit</tt> is the set limit of upload slots (unchoked peers) for this torrent.</p>
<p><tt class="docutils literal">connections_limit</tt> is the set limit of number of connections for this torrent.</p>
<p><tt class="docutils literal">storage_mode</tt> is one of <tt class="docutils literal">storage_mode_allocate</tt>, <tt class="docutils literal">storage_mode_sparse</tt> or
<tt class="docutils literal">storage_mode_compact</tt>. Identifies which storage mode this torrent is being saved
with. See <a class="reference internal" href="#storage-allocation">Storage allocation</a>.</p>
<p><tt class="docutils literal">up_bandwidth_queue</tt> and <tt class="docutils literal">down_bandwidth_queue</tt> are the number of peers in this
torrent that are waiting for more bandwidth quota from the torrent rate limiter.
This can determine if the rate you get from this torrent is bound by the torrents
limit or not. If there is no limit set on this torrent, the peers might still be
waiting for bandwidth quota from the global limiter, but then they are counted in
the <tt class="docutils literal">session_status</tt> object.</p>
<p><tt class="docutils literal">all_time_upload</tt> and <tt class="docutils literal">all_time_download</tt> are accumulated upload and download
payload byte counters. They are saved in and restored from resume data to keep totals
across sessions.</p>
<p><tt class="docutils literal">active_time</tt>, <tt class="docutils literal">finished_time</tt> and <tt class="docutils literal">seeding_time</tt> are second counters.
They keep track of the number of seconds this torrent has been active (not
paused) and the number of seconds it has been active while being finished and
active while being a seed. <tt class="docutils literal">seeding_time</tt> should be &lt;= <tt class="docutils literal">finished_time</tt> which
should be &lt;= <tt class="docutils literal">active_time</tt>. They are all saved in and restored from resume data,
to keep totals across sessions.</p>
<p><tt class="docutils literal">seed_rank</tt> is a rank of how important it is to seed the torrent, it is used
to determine which torrents to seed and which to queue. It is based on the peer
to seed ratio from the tracker scrape. For more information, see <a class="reference internal" href="#queuing">queuing</a>.</p>
<p><tt class="docutils literal">last_scrape</tt> is the number of seconds since this torrent acquired scrape data.
If it has never done that, this value is -1.</p>
<p><tt class="docutils literal">has_incoming</tt> is true if there has ever been an incoming connection attempt
to this torrent.'</p>
<p><tt class="docutils literal">sparse_regions</tt> the number of regions of non-downloaded pieces in the
torrent. This is an interesting metric on windows vista, since there is
a limit on the number of sparse regions in a single file there.</p>
<p><tt class="docutils literal">seed_mode</tt> is true if the torrent is in seed_mode. If the torrent was
started in seed mode, it will leave seed mode once all pieces have been
checked or as soon as one piece fails the hash check.</p>
<p><tt class="docutils literal">upload_mode</tt> is true if the torrent is blocked from downloading. This
typically happens when a disk write operation fails. If the torrent is
auto-managed, it will periodically be taken out of this state, in the
hope that the disk condition (be it disk full or permission errors) has
been resolved. If the torrent is not auto-managed, you have to explicitly
take it out of the upload mode by calling <a class="reference internal" href="#set-upload-mode">set_upload_mode()</a> on the
<a class="reference internal" href="#torrent-handle">torrent_handle</a>.</p>
<p><tt class="docutils literal">share_mode</tt> is true if the torrent is currently in share-mode, i.e.
not downloading the torrent, but just helping the swarm out.</p>
<p><tt class="docutils literal">super_seeding</tt> is true if the torrent is in super seeding mode.</p>
<p><tt class="docutils literal">added_time</tt> is the posix-time when this torrent was added. i.e. what
<tt class="docutils literal">time(NULL)</tt> returned at the time.</p>
<p><tt class="docutils literal">completed_time</tt> is the posix-time when this torrent was finished. If
the torrent is not yet finished, this is 0.</p>
<p><tt class="docutils literal">last_seen_complete</tt> is the time when we, or one of our peers, last
saw a complete copy of this torrent.</p>
<p><tt class="docutils literal">time_since_upload</tt> and <tt class="docutils literal">time_since_download</tt> are the number of
seconds since any peer last uploaded from this torrent and the last
time a downloaded piece passed the hash check, respectively.</p>
<p><tt class="docutils literal">queue_position</tt> is the position this torrent has in the download
queue. If the torrent is a seed or finished, this is -1.</p>
<p><tt class="docutils literal">need_save_resume</tt> is true if this torrent has unsaved changes
to its download state and statistics since the last resume data
was saved.</p>
<p><tt class="docutils literal">ip_filter_applies</tt> is true if the session global IP filter applies
to this torrent. This defaults to true.</p>
<p><tt class="docutils literal">info_hash</tt> is the info-hash of the torrent.</p>
<p><tt class="docutils literal">listen_port</tt> is the listen port this torrent is listening on for new
connections, if the torrent has its own listen socket. Only SSL torrents
have their own listen sockets. If the torrent doesn't have one, and is
accepting connections on the single listen socket, this is 0.</p>
</div>
<div class="section" id="peer-info">
<h1>peer_info</h1>
<p>It contains the following fields:</p>
<pre class="literal-block">
struct peer_info
{
        enum
        {
                interesting = 0x1,
                choked = 0x2,
                remote_interested = 0x4,
                remote_choked = 0x8,
                supports_extensions = 0x10,
                local_connection = 0x20,
                handshake = 0x40,
                connecting = 0x80,
                queued = 0x100,
                on_parole = 0x200,
                seed = 0x400,
                optimistic_unchoke = 0x800,
                snubbed = 0x1000,
                upload_only = 0x2000,
                endgame_mode = 0x4000,
                holepunched = 0x8000,
                rc4_encrypted = 0x100000,
                plaintext_encrypted = 0x200000
        };

        unsigned int flags;

        enum peer_source_flags
        {
                tracker = 0x1,
                dht = 0x2,
                pex = 0x4,
                lsd = 0x8
        };

        int source;

        // bitmask representing socket state
        enum bw_state { bw_idle = 0, bw_limit = 1, bw_network = 2, bw_disk = 4 };

        char read_state;
        char write_state;

        asio::ip::tcp::endpoint ip;
        int up_speed;
        int down_speed;
        int payload_up_speed;
        int payload_down_speed;
        size_type total_download;
        size_type total_upload;
        peer_id pid;
        bitfield pieces;
        int upload_limit;
        int download_limit;

        time_duration last_request;
        time_duration last_active;
        int request_timeout;

        int send_buffer_size;
        int used_send_buffer;

        int receive_buffer_size;
        int used_receive_buffer;

        int num_hashfails;

        char country[2];

        std::string inet_as_name;
        int inet_as;

        size_type load_balancing;

        int requests_in_buffer;
        int download_queue_length;
        int upload_queue_length;

        int failcount;

        int downloading_piece_index;
        int downloading_block_index;
        int downloading_progress;
        int downloading_total;

        std::string client;

        enum
        {
                standard_bittorrent = 0,
                web_seed = 1
        };
        int connection_type;

        int remote_dl_rate;

        int pending_disk_bytes;

        int send_quota;
        int receive_quota;

        int rtt;

        int num_pieces;

        int download_rate_peak;
        int upload_rate_peak;

        float progress;
        int progress_ppm;

        tcp::endpoint local_endpoint;
};
</pre>
<p>The <tt class="docutils literal">flags</tt> attribute tells you in which state the peer is. It is set to
any combination of the enums above. The following table describes each flag:</p>
<table border="1" class="docutils">
<colgroup>
<col width="31%" />
<col width="69%" />
</colgroup>
<tbody valign="top">
<tr><td><tt class="docutils literal">interesting</tt></td>
<td><strong>we</strong> are interested in pieces from this peer.</td>
</tr>
<tr><td><tt class="docutils literal">choked</tt></td>
<td><strong>we</strong> have choked this peer.</td>
</tr>
<tr><td><tt class="docutils literal">remote_interested</tt></td>
<td>the peer is interested in <strong>us</strong></td>
</tr>
<tr><td><tt class="docutils literal">remote_choked</tt></td>
<td>the peer has choked <strong>us</strong>.</td>
</tr>
<tr><td><tt class="docutils literal">support_extensions</tt></td>
<td>means that this peer supports the
<a class="reference external" href="extension_protocol.html">extension protocol</a>.</td>
</tr>
<tr><td><tt class="docutils literal">local_connection</tt></td>
<td>The connection was initiated by us, the peer has a
listen port open, and that port is the same as in the
address of this peer. If this flag is not set, this
peer connection was opened by this peer connecting to
us.</td>
</tr>
<tr><td><tt class="docutils literal">handshake</tt></td>
<td>The connection is opened, and waiting for the
handshake. Until the handshake is done, the peer
cannot be identified.</td>
</tr>
<tr><td><tt class="docutils literal">connecting</tt></td>
<td>The connection is in a half-open state (i.e. it is
being connected).</td>
</tr>
<tr><td><tt class="docutils literal">queued</tt></td>
<td>The connection is currently queued for a connection
attempt. This may happen if there is a limit set on
the number of half-open TCP connections.</td>
</tr>
<tr><td><tt class="docutils literal">on_parole</tt></td>
<td>The peer has participated in a piece that failed the
hash check, and is now &quot;on parole&quot;, which means we're
only requesting whole pieces from this peer until
it either fails that piece or proves that it doesn't
send bad data.</td>
</tr>
<tr><td><tt class="docutils literal">seed</tt></td>
<td>This peer is a seed (it has all the pieces).</td>
</tr>
<tr><td><tt class="docutils literal">optimistic_unchoke</tt></td>
<td>This peer is subject to an optimistic unchoke. It has
been unchoked for a while to see if it might unchoke
us in return an earn an upload/unchoke slot. If it
doesn't within some period of time, it will be choked
and another peer will be optimistically unchoked.</td>
</tr>
<tr><td><tt class="docutils literal">snubbed</tt></td>
<td>This peer has recently failed to send a block within
the request timeout from when the request was sent.
We're currently picking one block at a time from this
peer.</td>
</tr>
<tr><td><tt class="docutils literal">upload_only</tt></td>
<td>This peer has either explicitly (with an extension)
or implicitly (by becoming a seed) told us that it
will not downloading anything more, regardless of
which pieces we have.</td>
</tr>
<tr><td><tt class="docutils literal">endgame_mode</tt></td>
<td>This means the last time this peer picket a piece,
it could not pick as many as it wanted because there
were not enough free ones. i.e. all pieces this peer
has were already requested from other peers.</td>
</tr>
<tr><td><tt class="docutils literal">holepunched</tt></td>
<td>This flag is set if the peer was in holepunch mode
when the connection succeeded. This typically only
happens if both peers are behind a NAT and the peers
connect via the NAT holepunch mechanism.</td>
</tr>
</tbody>
</table>
<p><tt class="docutils literal">source</tt> is a combination of flags describing from which sources this peer
was received. The flags are:</p>
<table border="1" class="docutils">
<colgroup>
<col width="30%" />
<col width="70%" />
</colgroup>
<tbody valign="top">
<tr><td><tt class="docutils literal">tracker</tt></td>
<td>The peer was received from the tracker.</td>
</tr>
<tr><td><tt class="docutils literal">dht</tt></td>
<td>The peer was received from the kademlia DHT.</td>
</tr>
<tr><td><tt class="docutils literal">pex</tt></td>
<td>The peer was received from the peer exchange
extension.</td>
</tr>
<tr><td><tt class="docutils literal">lsd</tt></td>
<td>The peer was received from the local service
discovery (The peer is on the local network).</td>
</tr>
<tr><td><tt class="docutils literal">resume_data</tt></td>
<td>The peer was added from the fast resume data.</td>
</tr>
</tbody>
</table>
<p><tt class="docutils literal">read_state</tt> and <tt class="docutils literal">write_state</tt> are bitmasks indicating what state this peer
is in with regards to sending and receiving data. The states are declared in the
<tt class="docutils literal">bw_state</tt> enum and defines as follows:</p>
<table border="1" class="docutils">
<colgroup>
<col width="30%" />
<col width="70%" />
</colgroup>
<tbody valign="top">
<tr><td><tt class="docutils literal">bw_idle</tt></td>
<td>The peer is not waiting for any external events to
send or receive data.</td>
</tr>
<tr><td><tt class="docutils literal">bw_limit</tt></td>
<td>The peer is waiting for the rate limiter.</td>
</tr>
<tr><td><tt class="docutils literal">bw_network</tt></td>
<td>The peer has quota and is currently waiting for a
network read or write operation to complete. This is
the state all peers are in if there are no bandwidth
limits.</td>
</tr>
<tr><td><tt class="docutils literal">bw_disk</tt></td>
<td>The peer is waiting for the disk I/O thread to catch
up writing buffers to disk before downloading more.</td>
</tr>
</tbody>
</table>
<p>Note that <tt class="docutils literal">read_state</tt> and <tt class="docutils literal">write_state</tt> are bitmasks. A peer may be waiting
on disk and on the network at the same time. <tt class="docutils literal">bw_idle</tt> does not represent a bit,
but is simply a name for no bit being set in the bitmask.</p>
<p>The <tt class="docutils literal">ip</tt> field is the IP-address to this peer. The type is an asio endpoint. For
more info, see the <a class="reference external" href="http://asio.sf.net">asio</a> documentation.</p>
<p><tt class="docutils literal">up_speed</tt> and <tt class="docutils literal">down_speed</tt> contains the current upload and download speed
we have to and from this peer (including any protocol messages). The transfer rates
of payload data only are found in <tt class="docutils literal">payload_up_speed</tt> and <tt class="docutils literal">payload_down_speed</tt>.
These figures are updated approximately once every second.</p>
<p><tt class="docutils literal">total_download</tt> and <tt class="docutils literal">total_upload</tt> are the total number of bytes downloaded
from and uploaded to this peer. These numbers do not include the protocol chatter, but only
the payload data.</p>
<p><tt class="docutils literal">pid</tt> is the peer's id as used in the bit torrent protocol. This id can be used to
extract 'fingerprints' from the peer. Sometimes it can tell you which client the peer
is using. See identify_client()_</p>
<p><tt class="docutils literal">pieces</tt> is a bitfield, with one bit per piece in the torrent.
Each bit tells you if the peer has that piece (if it's set to 1)
or if the peer miss that piece (set to 0).</p>
<p><tt class="docutils literal">seed</tt> is true if this peer is a seed.</p>
<p><tt class="docutils literal">upload_limit</tt> is the number of bytes per second we are allowed to send to this
peer every second. It may be -1 if there's no local limit on the peer. The global
limit and the torrent limit is always enforced anyway.</p>
<p><tt class="docutils literal">download_limit</tt> is the number of bytes per second this peer is allowed to
receive. -1 means it's unlimited.</p>
<p><tt class="docutils literal">last_request</tt> and <tt class="docutils literal">last_active</tt> is the time since we last sent a request
to this peer and since any transfer occurred with this peer, respectively.</p>
<p><tt class="docutils literal">request_timeout</tt> is the number of seconds until the current front piece request
will time out. This timeout can be adjusted through <tt class="docutils literal"><span class="pre">session_settings::request_timeout</span></tt>.
-1 means that there is not outstanding request.</p>
<p><tt class="docutils literal">send_buffer_size</tt> and <tt class="docutils literal">used_send_buffer</tt> is the number of bytes allocated
and used for the peer's send buffer, respectively.</p>
<p><tt class="docutils literal">receive_buffer_size</tt> and <tt class="docutils literal">used_receive_buffer</tt> are the number of bytes
allocated and used as receive buffer, respectively.</p>
<p><tt class="docutils literal">num_hashfails</tt> is the number of pieces this peer has participated in
sending us that turned out to fail the hash check.</p>
<p><tt class="docutils literal">country</tt> is the two letter <a class="reference external" href="http://www.iso.org/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/list-en1.html">ISO 3166 country code</a> for the country the peer
is connected from. If the country hasn't been resolved yet, both chars are set
to 0. If the resolution failed for some reason, the field is set to &quot;--&quot;. If the
resolution service returns an invalid country code, it is set to &quot;!!&quot;.
The <tt class="docutils literal">countries.nerd.dk</tt> service is used to look up countries. This field will
remain set to 0 unless the torrent is set to resolve countries, see <a class="reference internal" href="#resolve-countries">resolve_countries()</a>.</p>
<p><tt class="docutils literal">inet_as_name</tt> is the name of the AS this peer is located in. This might be
an empty string if there is no name in the geo ip database.</p>
<p><tt class="docutils literal">inet_as</tt> is the AS number the peer is located in.</p>
<p><tt class="docutils literal">load_balancing</tt> is a measurement of the balancing of free download (that we get)
and free upload that we give. Every peer gets a certain amount of free upload, but
this member says how much <em>extra</em> free upload this peer has got. If it is a negative
number it means that this was a peer from which we have got this amount of free
download.</p>
<p><tt class="docutils literal">requests_in_buffer</tt> is the number of requests messages that are currently in the
send buffer waiting to be sent.</p>
<p><tt class="docutils literal">download_queue_length</tt> is the number of piece-requests we have sent to this peer
that hasn't been answered with a piece yet.</p>
<p><tt class="docutils literal">upload_queue_length</tt> is the number of piece-requests we have received from this peer
that we haven't answered with a piece yet.</p>
<p><tt class="docutils literal">failcount</tt> is the number of times this peer has &quot;failed&quot;. i.e. failed to connect
or disconnected us. The failcount is decremented when we see this peer in a tracker
response or peer exchange message.</p>
<p>You can know which piece, and which part of that piece, that is currently being
downloaded from a specific peer by looking at the next four members.
<tt class="docutils literal">downloading_piece_index</tt> is the index of the piece that is currently being downloaded.
This may be set to -1 if there's currently no piece downloading from this peer. If it is
&gt;= 0, the other three members are valid. <tt class="docutils literal">downloading_block_index</tt> is the index of the
block (or sub-piece) that is being downloaded. <tt class="docutils literal">downloading_progress</tt> is the number
of bytes of this block we have received from the peer, and <tt class="docutils literal">downloading_total</tt> is
the total number of bytes in this block.</p>
<p><tt class="docutils literal">client</tt> is a string describing the software at the other end of the connection.
In some cases this information is not available, then it will contain a string
that may give away something about which software is running in the other end.
In the case of a web seed, the server type and version will be a part of this
string.</p>
<p><tt class="docutils literal">connection_type</tt> can currently be one of:</p>
<table border="1" class="docutils">
<colgroup>
<col width="41%" />
<col width="59%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">type</th>
<th class="head">meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr><td><tt class="docutils literal"><span class="pre">peer_info::standard_bittorrent</span></tt></td>
<td>Regular bittorrent connection over TCP</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">peer_info::bittorrent_utp</span></tt></td>
<td>Bittorrent connection over uTP</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">peer_info::web_sesed</span></tt></td>
<td>HTTP connection using the <a class="reference external" href="http://bittorrent.org/beps/bep_0019.html">BEP 19</a> protocol</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">peer_info::http_seed</span></tt></td>
<td>HTTP connection using the <a class="reference external" href="http://bittorrent.org/beps/bep_0017.html">BEP 17</a> protocol</td>
</tr>
</tbody>
</table>
<p><tt class="docutils literal">remote_dl_rate</tt> is an estimate of the rate this peer is downloading at, in
bytes per second.</p>
<p><tt class="docutils literal">pending_disk_bytes</tt> is the number of bytes this peer has pending in the
disk-io thread. Downloaded and waiting to be written to disk. This is what
is capped by <tt class="docutils literal"><span class="pre">session_settings::max_queued_disk_bytes</span></tt>.</p>
<p><tt class="docutils literal">send_quota</tt> and <tt class="docutils literal">receive_quota</tt> are the number of bytes this peer has been
assigned to be allowed to send and receive until it has to request more quota
from the bandwidth manager.</p>
<p><tt class="docutils literal">rtt</tt> is an estimated round trip time to this peer, in milliseconds. It is
estimated by timing the the tcp <tt class="docutils literal">connect()</tt>. It may be 0 for incoming connections.</p>
<p><tt class="docutils literal">num_pieces</tt> is the number of pieces this peer has.</p>
<p><tt class="docutils literal">download_rate_peak</tt> and <tt class="docutils literal">upload_rate_peak</tt> are the highest download and upload
rates seen on this connection. They are given in bytes per second. This number is
reset to 0 on reconnect.</p>
<p><tt class="docutils literal">progress</tt> is the progress of the peer in the range [0, 1]. This is always 0 when
floating point operations are diabled, instead use <tt class="docutils literal">progress_ppm</tt>.</p>
<p><tt class="docutils literal">progress_ppm</tt> indicates the download progress of the peer in the range [0, 1000000]
(parts per million).</p>
<p><tt class="docutils literal">local_endpoint</tt> is the IP and port pair the socket is bound to locally. i.e. the IP
address of the interface it's going out over. This may be useful for multi-homed
clients with multiple interfaces to the internet.</p>
</div>
<div class="section" id="feed-handle">
<h1>feed_handle</h1>
<p>The <tt class="docutils literal">feed_handle</tt> refers to a specific RSS feed which is watched by the session.
The <tt class="docutils literal">feed_item</tt> struct is defined in <tt class="docutils literal">&lt;libtorrent/rss.hpp&gt;</tt>. It has the following
functions:</p>
<pre class="literal-block">
struct feed_handle
{
        feed_handle();
        void update_feed();
        feed_status get_feed_status() const;
        void set_settings(feed_settings const&amp; s);
        feed_settings settings() const;
};
</pre>
<div class="section" id="update-feed">
<h2>update_feed()</h2>
<blockquote>
<pre class="literal-block">
void update_feed();
</pre>
</blockquote>
<p>Forces an update/refresh of the feed. Regular updates of the feed is managed
by libtorrent, be careful to not call this too frequently since it may
overload the RSS server.</p>
</div>
<div class="section" id="get-feed-status">
<h2>get_feed_status()</h2>
<blockquote>
<pre class="literal-block">
feed_status get_feed_status() const;
</pre>
</blockquote>
<p>Queries the RSS feed for information, including all the items in the feed.
The <tt class="docutils literal">feed_status</tt> object has the following fields:</p>
<pre class="literal-block">
struct feed_status
{
        std::string url;
        std::string title;
        std::string description;
        time_t last_update;
        int next_update;
        bool updating;
        std::vector&lt;feed_item&gt; items;
        error_code error;
        int ttl;
};
</pre>
<p><tt class="docutils literal">url</tt> is the URL of the feed.</p>
<p><tt class="docutils literal">title</tt> is the name of the feed (as specified by the feed itself). This
may be empty if we have not recevied a response from the RSS server yet,
or if the feed does not specify a title.</p>
<p><tt class="docutils literal">description</tt> is the feed description (as specified by the feed itself).
This may be empty if we have not received a response from the RSS server
yet, or if the feed does not specify a description.</p>
<p><tt class="docutils literal">last_update</tt> is the posix time of the last successful response from the feed.</p>
<p><tt class="docutils literal">next_update</tt> is the number of seconds, from now, when the feed will be
updated again.</p>
<p><tt class="docutils literal">updating</tt> is true if the feed is currently being updated (i.e. waiting for
DNS resolution, connecting to the server or waiting for the response to the
HTTP request, or receiving the response).</p>
<p><tt class="docutils literal">items</tt> is a vector of all items that we have received from the feed. See
<a class="reference internal" href="#feed-item">feed_item</a> for more information.</p>
<p><tt class="docutils literal">error</tt> is set to the appropriate error code if the feed encountered an
error.</p>
<p><tt class="docutils literal">ttl</tt> is the current refresh time (in minutes). It's either the configured
default ttl, or the ttl specified by the feed.</p>
</div>
<div class="section" id="set-settings-settings">
<h2>set_settings() settings()</h2>
<blockquote>
<pre class="literal-block">
void set_settings(feed_settings const&amp; s);
feed_settings settings() const;
</pre>
</blockquote>
<p>Sets and gets settings for this feed. For more information on the
available settings, see <a class="reference internal" href="#add-feed">add_feed()</a>.</p>
</div>
</div>
<div class="section" id="feed-item">
<h1>feed_item</h1>
<p>The <tt class="docutils literal">feed_item</tt> struct is defined in <tt class="docutils literal">&lt;libtorrent/rss.hpp&gt;</tt>.</p>
<blockquote>
<pre class="literal-block">
struct feed_item
{
        feed_item();
        std::string url;
        std::string uuid;
        std::string title;
        std::string description;
        std::string comment;
        std::string category;
        size_type size;
        torrent_handle handle;
        sha1_hash info_hash;
};
</pre>
</blockquote>
<p><tt class="docutils literal">size</tt> is the total size of the content the torrent refers to, or -1
if no size was specified by the feed.</p>
<p><tt class="docutils literal">handle</tt> is the handle to the torrent, if the session is already downloading
this torrent.</p>
<p><tt class="docutils literal">info_hash</tt> is the info-hash of the torrent, or cleared (i.e. all zeroes) if
the feed does not specify the info-hash.</p>
<p>All the strings are self explanatory and may be empty if the feed does not specify
those fields.</p>
</div>
<div class="section" id="session-customization">
<h1>session customization</h1>
<p>You have some control over session configuration through the <tt class="docutils literal">session_settings</tt> object. You
create it and fill it with your settings and then use <tt class="docutils literal"><span class="pre">session::set_settings()</span></tt>
to apply them.</p>
<p>You have control over proxy and authorization settings and also the user-agent
that will be sent to the tracker. The user-agent will also be used to identify the
client with other peers.</p>
<div class="section" id="presets">
<h2>presets</h2>
<p>The default values of the session settings are set for a regular bittorrent client running
on a desktop system. There are functions that can set the session settings to pre set
settings for other environments. These can be used for the basis, and should be tweaked to
fit your needs better.</p>
<pre class="literal-block">
session_settings min_memory_usage();
session_settings high_performance_seed();
</pre>
<p><tt class="docutils literal">min_memory_usage</tt> returns settings that will use the minimal amount of RAM, at the
potential expense of upload and download performance. It adjusts the socket buffer sizes,
disables the disk cache, lowers the send buffer watermarks so that each connection only has
at most one block in use at any one time. It lowers the outstanding blocks send to the disk
I/O thread so that connections only have one block waiting to be flushed to disk at any given
time. It lowers the max number of peers in the peer list for torrents. It performs multiple
smaller reads when it hashes pieces, instead of reading it all into memory before hashing.</p>
<p>This configuration is inteded to be the starting point for embedded devices. It will
significantly reduce memory usage.</p>
<p><tt class="docutils literal">high_performance_seed</tt> returns settings optimized for a seed box, serving many peers
and that doesn't do any downloading. It has a 128 MB disk cache and has a limit of 400 files
in its file pool. It support fast upload rates by allowing large send buffers.</p>
</div>
<div class="section" id="session-settings">
<h2>session_settings</h2>
<pre class="literal-block">
struct session_settings
{
        session_settings();
        int version;
        std::string user_agent;
        int tracker_completion_timeout;
        int tracker_receive_timeout;
        int stop_tracker_timeout;
        int tracker_maximum_response_length;

        int piece_timeout;
        float request_queue_time;
        int max_allowed_in_request_queue;
        int max_out_request_queue;
        int whole_pieces_threshold;
        int peer_timeout;
        int urlseed_timeout;
        int urlseed_pipeline_size;
        int file_pool_size;
        bool allow_multiple_connections_per_ip;
        int max_failcount;
        int min_reconnect_time;
        int peer_connect_timeout;
        bool ignore_limits_on_local_network;
        int connection_speed;
        bool send_redundant_have;
        bool lazy_bitfields;
        int inactivity_timeout;
        int unchoke_interval;
        int optimistic_unchoke_interval;
        std::string announce_ip;
        int num_want;
        int initial_picker_threshold;
        int allowed_fast_set_size;

        enum { no_piece_suggestions = 0, suggest_read_cache = 1 };
        int suggest_mode;
        int max_queued_disk_bytes;
        int handshake_timeout;
        bool use_dht_as_fallback;
        bool free_torrent_hashes;
        bool upnp_ignore_nonrouters;
        int send_buffer_watermark;
        int send_buffer_watermark_factor;

#ifndef TORRENT_NO_DEPRECATE
        bool auto_upload_slots;
        bool auto_upload_slots_rate_based;
#endif

        enum choking_algorithm_t
        {
                fixed_slots_choker,
                auto_expand_choker,
                rate_based_choker,
                bittyrant_choker
        };

        int choking_algorithm;

        enum seed_choking_algorithm_t
        {
                round_robin,
                fastest_upload,
                anti_leech
        };

        int seed_choking_algorithm;

        bool use_parole_mode;
        int cache_size;
        int cache_buffer_chunk_size;
        int cache_expiry;
        bool use_read_cache;
        bool explicit_read_cache;
        int explicit_cache_interval;

        enum io_buffer_mode_t
        {
                enable_os_cache = 0,
                disable_os_cache_for_aligned_files = 1,
                disable_os_cache = 2
        };
        int disk_io_write_mode;
        int disk_io_read_mode;

        std::pair&lt;int, int&gt; outgoing_ports;
        char peer_tos;

        int active_downloads;
        int active_seeds;
        int active_dht_limit;
        int active_tracker_limit;
        int active_limit;
        bool auto_manage_prefer_seeds;
        bool dont_count_slow_torrents;
        int auto_manage_interval;
        float share_ratio_limit;
        float seed_time_ratio_limit;
        int seed_time_limit;
        int peer_turnover_interval;
        float peer_turnover;
        float peer_turnover_cutoff;
        bool close_redundant_connections;

        int auto_scrape_interval;
        int auto_scrape_min_interval;

        int max_peerlist_size;

        int min_announce_interval;

        bool prioritize_partial_pieces;
        int auto_manage_startup;

        bool rate_limit_ip_overhead;

        bool announce_to_all_trackers;
        bool announce_to_all_tiers;

        bool prefer_udp_trackers;
        bool strict_super_seeding;

        int seeding_piece_quota;

        int max_sparse_regions;

        bool lock_disk_cache;

        int max_rejects;

        int recv_socket_buffer_size;
        int send_socket_buffer_size;

        bool optimize_hashing_for_speed;

        int file_checks_delay_per_block;

        enum disk_cache_algo_t
        { lru, largest_contiguous, avoid_readback };

        disk_cache_algo_t disk_cache_algorithm;

        int read_cache_line_size;
        int write_cache_line_size;

        int optimistic_disk_retry;
        bool disable_hash_check;

        int max_suggest_pieces;

        bool drop_skipped_requests;

        bool low_prio_disk;
        int local_service_announce_interval;
        int dht_announce_interval;

        int udp_tracker_token_expiry;
        bool volatile_read_cache;
        bool guided_read_cache;
        bool default_min_cache_age;

        int num_optimistic_unchoke_slots;
        bool no_atime_storage;
        int default_est_reciprocation_rate;
        int increase_est_reciprocation_rate;
        int decrease_est_reciprocation_rate;
        bool incoming_starts_queued_torrents;
        bool report_true_downloaded;
        bool strict_end_game_mode;

        bool broadcast_lsd;

        bool enable_outgoing_utp;
        bool enable_incoming_utp;
        bool enable_outgoing_tcp;
        bool enable_incoming_tcp;
        int max_pex_peers;
        bool ignore_resume_timestamps;
        bool no_recheck_incomplete_resume;
        bool anonymous_mode;
        int tick_interval;
        int share_mode_target;

        int upload_rate_limit;
        int download_rate_limit;
        int local_upload_rate_limit;
        int local_download_rate_limit;
        int dht_upload_rate_limit;
        int unchoke_slots_limit;
        int half_open_limit;
        int connections_limit;

        int utp_target_delay;
        int utp_gain_factor;
        int utp_min_timeout;
        int utp_syn_resends;
        int utp_num_resends;
        int utp_connect_timeout;
        bool utp_dynamic_sock_buf;
        int utp_loss_multiplier;

        enum bandwidth_mixed_algo_t
        {
                prefer_tcp = 0,
                peer_proportional = 1

        };
        int mixed_mode_algorithm;
        bool rate_limit_utp;

        int listen_queue_size;

        bool announce_double_nat;

        int torrent_connect_boost;
        bool seeding_outgoing_connections;

        bool no_connect_privileged_ports;
        int alert_queue_size;
        int max_metadata_size;
        bool smooth_connects;
        bool always_send_user_agent;
        bool apply_ip_filter_to_trackers;
        int read_job_every;
        bool use_disk_read_ahead;
        bool lock_files;

        int ssl_listen;

        int tracker_backoff;

        bool ban_web_seeds;
        int max_http_recv_buffer_size;
};
</pre>
<p><tt class="docutils literal">version</tt> is automatically set to the libtorrent version you're using
in order to be forward binary compatible. This field should not be changed.</p>
<p><tt class="docutils literal">user_agent</tt> this is the client identification to the tracker.
The recommended format of this string is:
&quot;ClientName/ClientVersion libtorrent/libtorrentVersion&quot;.
This name will not only be used when making HTTP requests, but also when
sending extended headers to peers that support that extension.</p>
<p><tt class="docutils literal">tracker_completion_timeout</tt> is the number of seconds the tracker
connection will wait from when it sent the request until it considers the
tracker to have timed-out. Default value is 60 seconds.</p>
<p><tt class="docutils literal">tracker_receive_timeout</tt> is the number of seconds to wait to receive
any data from the tracker. If no data is received for this number of
seconds, the tracker will be considered as having timed out. If a tracker
is down, this is the kind of timeout that will occur. The default value
is 20 seconds.</p>
<p><tt class="docutils literal">stop_tracker_timeout</tt> is the time to wait for tracker responses when
shutting down the session object. This is given in seconds. Default is
10 seconds.</p>
<p><tt class="docutils literal">tracker_maximum_response_length</tt> is the maximum number of bytes in a
tracker response. If a response size passes this number it will be rejected
and the connection will be closed. On gzipped responses this size is measured
on the uncompressed data. So, if you get 20 bytes of gzip response that'll
expand to 2 megs, it will be interrupted before the entire response has been
uncompressed (given your limit is lower than 2 megs). Default limit is
1 megabyte.</p>
<p><tt class="docutils literal">piece_timeout</tt> controls the number of seconds from a request is sent until
it times out if no piece response is returned.</p>
<p><tt class="docutils literal">request_queue_time</tt> is the length of the request queue given in the number
of seconds it should take for the other end to send all the pieces. i.e. the
actual number of requests depends on the download rate and this number.</p>
<p><tt class="docutils literal">max_allowed_in_request_queue</tt> is the number of outstanding block requests
a peer is allowed to queue up in the client. If a peer sends more requests
than this (before the first one has been handled) the last request will be
dropped. The higher this is, the faster upload speeds the client can get to a
single peer.</p>
<p><tt class="docutils literal">max_out_request_queue</tt> is the maximum number of outstanding requests to
send to a peer. This limit takes precedence over <tt class="docutils literal">request_queue_time</tt>. i.e.
no matter the download speed, the number of outstanding requests will never
exceed this limit.</p>
<p><tt class="docutils literal">whole_pieces_threshold</tt> is a limit in seconds. if a whole piece can be
downloaded in at least this number of seconds from a specific peer, the
peer_connection will prefer requesting whole pieces at a time from this peer.
The benefit of this is to better utilize disk caches by doing localized
accesses and also to make it easier to identify bad peers if a piece fails
the hash check.</p>
<p><tt class="docutils literal">peer_timeout</tt> is the number of seconds the peer connection should
wait (for any activity on the peer connection) before closing it due
to time out. This defaults to 120 seconds, since that's what's specified
in the protocol specification. After half the time out, a keep alive message
is sent.</p>
<p><tt class="docutils literal">urlseed_timeout</tt> is the same as <tt class="docutils literal">peer_timeout</tt> but applies only to
url seeds. This value defaults to 20 seconds.</p>
<p><tt class="docutils literal">urlseed_pipeline_size</tt> controls the pipelining with the web server. When
using persistent connections to HTTP 1.1 servers, the client is allowed to
send more requests before the first response is received. This number controls
the number of outstanding requests to use with url-seeds. Default is 5.</p>
<p><tt class="docutils literal">file_pool_size</tt> is the the upper limit on the total number of files this
session will keep open. The reason why files are left open at all is that
some anti virus software hooks on every file close, and scans the file for
viruses. deferring the closing of the files will be the difference between
a usable system and a completely hogged down system. Most operating systems
also has a limit on the total number of file descriptors a process may have
open. It is usually a good idea to find this limit and set the number of
connections and the number of files limits so their sum is slightly below it.</p>
<p><tt class="docutils literal">allow_multiple_connections_per_ip</tt> determines if connections from the
same IP address as existing connections should be rejected or not. Multiple
connections from the same IP address is not allowed by default, to prevent
abusive behavior by peers. It may be useful to allow such connections in
cases where simulations are run on the same machie, and all peers in a
swarm has the same IP address.</p>
<p><tt class="docutils literal">max_failcount</tt> is the maximum times we try to connect to a peer before
stop connecting again. If a peer succeeds, the failcounter is reset. If
a peer is retrieved from a peer source (other than DHT) the failcount is
decremented by one, allowing another try.</p>
<p><tt class="docutils literal">min_reconnect_time</tt> is the time to wait between connection attempts. If
the peer fails, the time is multiplied by fail counter.</p>
<p><tt class="docutils literal">peer_connect_timeout</tt> the number of seconds to wait after a connection
attempt is initiated to a peer until it is considered as having timed out.
The default is 10 seconds. This setting is especially important in case
the number of half-open connections are limited, since stale half-open
connection may delay the connection of other peers considerably.</p>
<p><tt class="docutils literal">ignore_limits_on_local_network</tt>, if set to true, upload, download and
unchoke limits are ignored for peers on the local network.</p>
<p><tt class="docutils literal">connection_speed</tt> is the number of connection attempts that
are made per second. If a number &lt; 0 is specified, it will default to
200 connections per second. If 0 is specified, it means don't make
outgoing connections at all.</p>
<p><tt class="docutils literal">send_redundant_have</tt> controls if have messages will be sent
to peers that already have the piece. This is typically not necessary,
but it might be necessary for collecting statistics in some cases.
Default is false.</p>
<p><tt class="docutils literal">lazy_bitfields</tt> prevents outgoing bitfields from being full. If the
client is seed, a few bits will be set to 0, and later filled in with
have-messages. This is to prevent certain ISPs from stopping people
from seeding.</p>
<p><tt class="docutils literal">inactivity_timeout</tt>, if a peer is uninteresting and uninterested
for longer than this number of seconds, it will be disconnected.
Default is 10 minutes</p>
<p><tt class="docutils literal">unchoke_interval</tt> is the number of seconds between chokes/unchokes.
On this interval, peers are re-evaluated for being choked/unchoked. This
is defined as 30 seconds in the protocol, and it should be significantly
longer than what it takes for TCP to ramp up to it's max rate.</p>
<p><tt class="docutils literal">optimistic_unchoke_interval</tt> is the number of seconds between
each <em>optimistic</em> unchoke. On this timer, the currently optimistically
unchoked peer will change.</p>
<p><tt class="docutils literal">announce_ip</tt> is the ip address passed along to trackers as the <tt class="docutils literal">&amp;ip=</tt> parameter.
If left as the default (an empty string), that parameter is omitted.</p>
<p><tt class="docutils literal">num_want</tt> is the number of peers we want from each tracker request. It defines
what is sent as the <tt class="docutils literal">&amp;num_want=</tt> parameter to the tracker.</p>
<p><tt class="docutils literal">initial_picker_threshold</tt> specifies the number of pieces we need before we
switch to rarest first picking. This defaults to 4, which means the 4 first
pieces in any torrent are picked at random, the following pieces are picked
in rarest first order.</p>
<p><tt class="docutils literal">allowed_fast_set_size</tt> is the number of pieces we allow peers to download
from us without being unchoked.</p>
<p><tt class="docutils literal">suggest_mode</tt> controls whether or not libtorrent will send out suggest
messages to create a bias of its peers to request certain pieces. The modes
are:</p>
<ul class="simple">
<li><tt class="docutils literal">no_piece_suggestsions</tt> which is the default and will not send out suggest
messages.</li>
<li><tt class="docutils literal">suggest_read_cache</tt> which will send out suggest messages for the most
recent pieces that are in the read cache.</li>
</ul>
<p><tt class="docutils literal">max_queued_disk_bytes</tt> is the number maximum number of bytes, to be
written to disk, that can wait in the disk I/O thread queue. This queue
is only for waiting for the disk I/O thread to receive the job and either
write it to disk or insert it in the write cache. When this limit is reached,
the peer connections will stop reading data from their sockets, until the disk
thread catches up. Setting this too low will severly limit your download rate.</p>
<p><tt class="docutils literal">handshake_timeout</tt> specifies the number of seconds we allow a peer to
delay responding to a protocol handshake. If no response is received within
this time, the connection is closed.</p>
<p><tt class="docutils literal">use_dht_as_fallback</tt> determines how the DHT is used. If this is true,
the DHT will only be used for torrents where all trackers in its tracker
list has failed. Either by an explicit error message or a time out. This
is false by default, which means the DHT is used by default regardless of
if the trackers fail or not.</p>
<p><tt class="docutils literal">free_torrent_hashes</tt> determines whether or not the torrent's piece hashes
are kept in memory after the torrent becomes a seed or not. If it is set to
<tt class="docutils literal">true</tt> the hashes are freed once the torrent is a seed (they're not
needed anymore since the torrent won't download anything more). If it's set
to false they are not freed. If they are freed, the <a class="reference internal" href="#torrent-info">torrent_info</a> returned
by get_torrent_info() will return an object that may be incomplete, that
cannot be passed back to <a class="reference internal" href="#async-add-torrent-add-torrent">async_add_torrent() add_torrent()</a> for instance.</p>
<p><tt class="docutils literal">upnp_ignore_nonrouters</tt> indicates whether or not the UPnP implementation
should ignore any broadcast response from a device whose address is not the
configured router for this machine. i.e. it's a way to not talk to other
people's routers by mistake.</p>
<p><tt class="docutils literal">send_buffer_watermark</tt> is the upper limit of the send buffer low-watermark.
if the send buffer has fewer bytes than this, we'll read another 16kB block
onto it. If set too small, upload rate capacity will suffer. If set too high,
memory will be wasted. The actual watermark may be lower than this in case
the upload rate is low, this is the upper limit.</p>
<p><tt class="docutils literal">send_buffer_watermark_factor</tt> is multiplied to the peer's upload rate
to determine the low-watermark for the peer. It is specified as a percentage,
which means 100 represents a factor of 1.
The low-watermark is still clamped to not exceed the <tt class="docutils literal">send_buffer_watermark</tt>
upper limit. This defaults to 50. For high capacity connections, setting this
higher can improve upload performance and disk throughput. Setting it too
high may waste RAM and create a bias towards read jobs over write jobs.</p>
<p><tt class="docutils literal">auto_upload_slots</tt> defaults to true. When true, if there is a global upload
limit set and the current upload rate is less than 90% of that, another upload
slot is opened. If the upload rate has been saturated for an extended period
of time, on upload slot is closed. The number of upload slots will never be
less than what has been set by <tt class="docutils literal"><span class="pre">session::set_max_uploads()</span></tt>. To query the
current number of upload slots, see <tt class="docutils literal"><span class="pre">session_status::allowed_upload_slots</span></tt>.</p>
<p>When <tt class="docutils literal">auto_upload_slots_rate_based</tt> is set, and <tt class="docutils literal">auto_upload_slots</tt> is set,
the max upload slots setting is used as a minimum number of unchoked slots.
This algorithm is designed to prevent the peer from spreading its upload
capacity too thin, but still open more slots in order to utilize the full capacity.</p>
<p><tt class="docutils literal">choking_algorithm</tt> specifies which algorithm to use to determine which peers
to unchoke. This setting replaces the deprecated settings <tt class="docutils literal">auto_upload_slots</tt>
and <tt class="docutils literal">auto_upload_slots_rate_based</tt>.</p>
<p>The options for choking algorithms are:</p>
<ul class="simple">
<li><tt class="docutils literal">fixed_slots_choker</tt> is the traditional choker with a fixed number of unchoke
slots (as specified by <tt class="docutils literal"><span class="pre">session::set_max_uploads()</span></tt>).</li>
<li><tt class="docutils literal">auto_expand_choker</tt> opens at least the number of slots as specified by
<tt class="docutils literal"><span class="pre">session::set_max_uploads()</span></tt> but opens up more slots if the upload capacity
is not saturated. This unchoker will work just like the <tt class="docutils literal">fixed_slot_choker</tt>
if there's no global upload rate limit set.</li>
<li><tt class="docutils literal">rate_based_choker</tt> opens up unchoke slots based on the upload rate
achieved to peers. The more slots that are opened, the marginal upload
rate required to open up another slot increases.</li>
<li><tt class="docutils literal">bittyrant_choker</tt> attempts to optimize download rate by finding the
reciprocation rate of each peer individually and prefers peers that gives
the highest <em>return on investment</em>. It still allocates all upload capacity,
but shuffles it around to the best peers first. For this choker to be
efficient, you need to set a global upload rate limit
(<tt class="docutils literal"><span class="pre">session::set_upload_rate_limit()</span></tt>). For more information about this
choker, see the <a class="reference external" href="http://bittyrant.cs.washington.edu/#papers">paper</a>.</li>
</ul>
<p><tt class="docutils literal">seed_choking_algorithm</tt> controls the seeding unchoke behavior. The available
options are:</p>
<ul class="simple">
<li><tt class="docutils literal">round_robin</tt> which round-robins the peers that are unchoked when seeding. This
distributes the upload bandwidht uniformly and fairly. It minimizes the ability
for a peer to download everything without redistributing it.</li>
<li><tt class="docutils literal">fastest_upload</tt> unchokes the peers we can send to the fastest. This might be
a bit more reliable in utilizing all available capacity.</li>
<li><tt class="docutils literal">anti_leech</tt> prioritizes peers who have just started or are just about to finish
the download. The intention is to force peers in the middle of the download to
trade with each other.</li>
</ul>
<p><tt class="docutils literal">use_parole_mode</tt> specifies if parole mode should be used. Parole mode means
that peers that participate in pieces that fail the hash check are put in a mode
where they are only allowed to download whole pieces. If the whole piece a peer
in parole mode fails the hash check, it is banned. If a peer participates in a
piece that passes the hash check, it is taken out of parole mode.</p>
<p><tt class="docutils literal">cache_size</tt> is the disk write and read  cache. It is specified in units of
16 KiB blocks. Buffers that are part of a peer's send or receive buffer also
count against this limit. Send and receive buffers will never be denied to be
allocated, but they will cause the actual cached blocks to be flushed or evicted.
If this is set to -1, the cache size is automatically set to the amount
of physical RAM available in the machine divided by 8. If the amount of physical
RAM cannot be determined, it's set to 1024 (= 16 MiB).</p>
<p>Disk buffers are allocated using a pool allocator, the number of blocks that
are allocated at a time when the pool needs to grow can be specified in
<tt class="docutils literal">cache_buffer_chunk_size</tt>. This defaults to 16 blocks. Lower numbers
saves memory at the expense of more heap allocations. It must be at least 1.</p>
<p><tt class="docutils literal">cache_expiry</tt> is the number of seconds from the last cached write to a piece
in the write cache, to when it's forcefully flushed to disk. Default is 60 second.</p>
<p><tt class="docutils literal">use_read_cache</tt>, is set to true (default), the disk cache is also used to
cache pieces read from disk. Blocks for writing pieces takes presedence.</p>
<p><tt class="docutils literal">explicit_read_cache</tt> defaults to 0. If set to something greater than 0, the
disk read cache will not be evicted by cache misses and will explicitly be
controlled based on the rarity of pieces. Rare pieces are more likely to be
cached. This would typically be used together with <tt class="docutils literal">suggest_mode</tt> set to
<tt class="docutils literal">suggest_read_cache</tt>. The value is the number of pieces to keep in the read
cache. If the actual read cache can't fit as many, it will essentially be clamped.</p>
<p><tt class="docutils literal">explicit_cache_interval</tt> is the number of seconds in between each refresh of
a part of the explicit read cache. Torrents take turns in refreshing and this
is the time in between each torrent refresh. Refreshing a torrent's explicit
read cache means scanning all pieces and picking a random set of the rarest ones.
There is an affinity to pick pieces that are already in the cache, so that
subsequent refreshes only swaps in pieces that are rarer than whatever is in
the cache at the time.</p>
<p><tt class="docutils literal">disk_io_write_mode</tt> and <tt class="docutils literal">disk_io_read_mode</tt> determines how files are
opened when they're in read only mode versus read and write mode. The options
are:</p>
<blockquote>
<ul>
<li><dl class="first docutils">
<dt>enable_os_cache</dt>
<dd><p class="first last">This is the default and files are opened normally, with the OS caching
reads and writes.</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt>disable_os_cache_for_aligned_files</dt>
<dd><p class="first last">This will open files in unbuffered mode for files where every read and
write would be sector aligned. Using aligned disk offsets is a requirement
on some operating systems.</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt>disable_os_cache</dt>
<dd><p class="first last">This opens all files in unbuffered mode (if allowed by the operating system).
Linux and Windows, for instance, require disk offsets to be sector aligned,
and in those cases, this option is the same as <tt class="docutils literal">disable_os_caches_for_aligned_files</tt>.</p>
</dd>
</dl>
</li>
</ul>
</blockquote>
<p>One reason to disable caching is that it may help the operating system from growing
its file cache indefinitely. Since some OSes only allow aligned files to be opened
in unbuffered mode, It is recommended to make the largest file in a torrent the first
file (with offset 0) or use pad files to align all files to piece boundries.</p>
<p><tt class="docutils literal">outgoing_ports</tt>, if set to something other than (0, 0) is a range of ports
used to bind outgoing sockets to. This may be useful for users whose router
allows them to assign QoS classes to traffic based on its local port. It is
a range instead of a single port because of the problems with failing to reconnect
to peers if a previous socket to that peer and port is in <tt class="docutils literal">TIME_WAIT</tt> state.</p>
<div class="warning">
<p class="first admonition-title">Warning</p>
<p class="last">setting outgoing ports will limit the ability to keep multiple
connections to the same client, even for different torrents. It is not
recommended to change this setting. Its main purpose is to use as an
escape hatch for cheap routers with QoS capability but can only classify
flows based on port numbers.</p>
</div>
<p><tt class="docutils literal">peer_tos</tt> determines the TOS byte set in the IP header of every packet
sent to peers (including web seeds). The default value for this is <tt class="docutils literal">0x0</tt>
(no marking). One potentially useful TOS mark is <tt class="docutils literal">0x20</tt>, this represents
the <em>QBone scavenger service</em>. For more details, see <a class="reference external" href="http://qbone.internet2.edu/qbss/">QBSS</a>.</p>
<p><tt class="docutils literal">active_downloads</tt> and <tt class="docutils literal">active_seeds</tt> controls how many active seeding and
downloading torrents the queuing mechanism allows. The target number of active
torrents is <tt class="docutils literal">min(active_downloads + active_seeds, active_limit)</tt>.
<tt class="docutils literal">active_downloads</tt> and <tt class="docutils literal">active_seeds</tt> are upper limits on the number of
downloading torrents and seeding torrents respectively. Setting the value to
-1 means unlimited.</p>
<p>For example if there are 10 seeding torrents and 10 downloading torrents, and
<tt class="docutils literal">active_downloads</tt> is 4 and <tt class="docutils literal">active_seeds</tt> is 4, there will be 4 seeds
active and 4 downloading torrents. If the settings are <tt class="docutils literal">active_downloads</tt> = 2
and <tt class="docutils literal">active_seeds</tt> = 4, then there will be 2 downloading torrents and 4 seeding
torrents active. Torrents that are not auto managed are also counted against these
limits. If there are non-auto managed torrents that use up all the slots, no
auto managed torrent will be activated.</p>
<p><tt class="docutils literal">auto_manage_prefer_seeds</tt> specifies if libtorrent should prefer giving seeds
active slots or downloading torrents.  The default is <tt class="docutils literal">false</tt>.</p>
<p>if <tt class="docutils literal">dont_count_slow_torrents</tt> is true, torrents without any payload transfers are
not subject to the <tt class="docutils literal">active_seeds</tt> and <tt class="docutils literal">active_downloads</tt> limits. This is intended
to make it more likely to utilize all available bandwidth, and avoid having torrents
that don't transfer anything block the active slots.</p>
<p><tt class="docutils literal">active_limit</tt> is a hard limit on the number of active torrents. This applies even to
slow torrents.</p>
<p><tt class="docutils literal">active_dht_limit</tt> is the max number of torrents to announce to the DHT. By default
this is set to 88, which is no more than one DHT announce every 10 seconds.</p>
<p><tt class="docutils literal">active_tracker_limit</tt> is the max number of torrents to announce to their trackers.
By default this is 360, which is no more than one announce every 5 seconds.</p>
<p><tt class="docutils literal">active_lsd_limit</tt> is the max number of torrents to announce to the local network
over the local service discovery protocol. By default this is 80, which is no more
than one announce every 5 seconds (assuming the default announce interval of 5 minutes).</p>
<p>You can have more torrents <em>active</em>, even though they are not announced to the DHT,
lsd or their tracker. If some peer knows about you for any reason and tries to connect,
it will still be accepted, unless the torrent is paused, which means it won't accept
any connections.</p>
<p><tt class="docutils literal">auto_manage_interval</tt> is the number of seconds between the torrent queue
is updated, and rotated.</p>
<p><tt class="docutils literal">share_ratio_limit</tt> is the upload / download ratio limit for considering a
seeding torrent have met the seed limit criteria. See <a class="reference internal" href="#queuing">queuing</a>.</p>
<p><tt class="docutils literal">seed_time_ratio_limit</tt> is the seeding time / downloading time ratio limit
for considering a seeding torrent to have met the seed limit criteria. See <a class="reference internal" href="#queuing">queuing</a>.</p>
<p><tt class="docutils literal">seed_time_limit</tt> is the limit on the time a torrent has been an active seed
(specified in seconds) before it is considered having met the seed limit criteria.
See <a class="reference internal" href="#queuing">queuing</a>.</p>
<p><tt class="docutils literal">peer_turnover_interval</tt> controls a feature where libtorrent periodically can disconnect
the least useful peers in the hope of connecting to better ones. This settings controls
the interval of this optimistic disconnect. It defaults to every 5 minutes, and
is specified in seconds.</p>
<p><tt class="docutils literal">peer_turnover</tt> Is the fraction of the peers that are disconnected. This is
a float where 1.f represents all peers an 0 represents no peers. It defaults to
4% (i.e. 0.04f)</p>
<p><tt class="docutils literal">peer_turnover_cutoff</tt> is the cut off trigger for optimistic unchokes. If a torrent
has more than this fraction of its connection limit, the optimistic unchoke is
triggered. This defaults to 90% (i.e. 0.9f).</p>
<p><tt class="docutils literal">close_redundant_connections</tt> specifies whether libtorrent should close
connections where both ends have no utility in keeping the connection open.
For instance if both ends have completed their downloads, there's no point
in keeping it open. This defaults to <tt class="docutils literal">true</tt>.</p>
<p><tt class="docutils literal">auto_scrape_interval</tt> is the number of seconds between scrapes of
queued torrents (auto managed and paused torrents). Auto managed
torrents that are paused, are scraped regularly in order to keep
track of their downloader/seed ratio. This ratio is used to determine
which torrents to seed and which to pause.</p>
<p><tt class="docutils literal">auto_scrape_min_interval</tt> is the minimum number of seconds between any
automatic scrape (regardless of torrent). In case there are a large number
of paused auto managed torrents, this puts a limit on how often a scrape
request is sent.</p>
<p><tt class="docutils literal">max_peerlist_size</tt> is the maximum number of peers in the list of
known peers. These peers are not necessarily connected, so this number
should be much greater than the maximum number of connected peers.
Peers are evicted from the cache when the list grows passed 90% of
this limit, and once the size hits the limit, peers are no longer
added to the list. If this limit is set to 0, there is no limit on
how many peers we'll keep in the peer list.</p>
<p><tt class="docutils literal">max_paused_peerlist_size</tt> is the max peer list size used for torrents
that are paused. This default to the same as <tt class="docutils literal">max_peerlist_size</tt>, but
can be used to save memory for paused torrents, since it's not as
important for them to keep a large peer list.</p>
<p><tt class="docutils literal">min_announce_interval</tt> is the minimum allowed announce interval
for a tracker. This is specified in seconds, defaults to 5 minutes and
is used as a sanity check on what is returned from a tracker. It
mitigates hammering misconfigured trackers.</p>
<p>If <tt class="docutils literal">prioritize_partial_pieces</tt> is true, partial pieces are picked
before pieces that are more rare. If false, rare pieces are always
prioritized, unless the number of partial pieces is growing out of
proportion.</p>
<p><tt class="docutils literal">auto_manage_startup</tt> is the number of seconds a torrent is considered
active after it was started, regardless of upload and download speed. This
is so that newly started torrents are not considered inactive until they
have a fair chance to start downloading.</p>
<p>If <tt class="docutils literal">rate_limit_ip_overhead</tt> is set to true, the estimated TCP/IP overhead is
drained from the rate limiters, to avoid exceeding the limits with the total traffic</p>
<p><tt class="docutils literal">announce_to_all_trackers</tt> controls how multi tracker torrents are
treated. If this is set to true, all trackers in the same tier are
announced to in parallel. If all trackers in tier 0 fails, all trackers
in tier 1 are announced as well. If it's set to false, the behavior is as
defined by the multi tracker specification. It defaults to false, which
is the same behavior previous versions of libtorrent has had as well.</p>
<p><tt class="docutils literal">announce_to_all_tiers</tt> also controls how multi tracker torrents are
treated. When this is set to true, one tracker from each tier is announced
to. This is the uTorrent behavior. This is false by default in order
to comply with the multi-tracker specification.</p>
<p><tt class="docutils literal">prefer_udp_trackers</tt> is true by default. It means that trackers may
be rearranged in a way that udp trackers are always tried before http
trackers for the same hostname. Setting this to fails means that the
trackers' tier is respected and there's no preference of one protocol
over another.</p>
<p><tt class="docutils literal">strict_super_seeding</tt> when this is set to true, a piece has to
have been forwarded to a third peer before another one is handed out.
This is the traditional definition of super seeding.</p>
<p><tt class="docutils literal">seeding_piece_quota</tt> is the number of pieces to send to a peer,
when seeding, before rotating in another peer to the unchoke set.
It defaults to 3 pieces, which means that when seeding, any peer we've
sent more than this number of pieces to will be unchoked in favour of
a choked peer.</p>
<p><tt class="docutils literal">max_sparse_regions</tt> is a limit of the number of <em>sparse regions</em> in
a torrent. A sparse region is defined as a hole of pieces we have not
yet downloaded, in between pieces that have been downloaded. This is
used as a hack for windows vista which has a bug where you cannot
write files with more than a certain number of sparse regions. This
limit is not hard, it will be exceeded. Once it's exceeded, pieces
that will maintain or decrease the number of sparse regions are
prioritized. To disable this functionality, set this to 0. It defaults
to 0 on all platforms except windows.</p>
<p><tt class="docutils literal">lock_disk_cache</tt> if lock disk cache is set to true the disk cache
that's in use, will be locked in physical memory, preventing it from
being swapped out.</p>
<p><tt class="docutils literal">max_rejects</tt> is the number of piece requests we will reject in a row
while a peer is choked before the peer is considered abusive and is
disconnected.</p>
<p><tt class="docutils literal">recv_socket_buffer_size</tt> and <tt class="docutils literal">send_socket_buffer_size</tt> specifies
the buffer sizes set on peer sockets. 0 (which is the default) means
the OS default (i.e. don't change the buffer sizes). The socket buffer
sizes are changed using setsockopt() with SOL_SOCKET/SO_RCVBUF and
SO_SNDBUFFER.</p>
<p><tt class="docutils literal">optimize_hashing_for_speed</tt> chooses between two ways of reading back
piece data from disk when its complete and needs to be verified against
the piece hash. This happens if some blocks were flushed to the disk
out of order. Everything that is flushed in order is hashed as it goes
along. Optimizing for speed will allocate space to fit all the the
remaingin, unhashed, part of the piece, reads the data into it in a single
call and hashes it. This is the default. If <tt class="docutils literal">optimizing_hashing_for_speed</tt>
is false, a single block will be allocated (16 kB), and the unhashed parts
of the piece are read, one at a time, and hashed in this single block. This
is appropriate on systems that are memory constrained.</p>
<p><tt class="docutils literal">file_checks_delay_per_block</tt> is the number of milliseconds to sleep
in between disk read operations when checking torrents. This defaults
to 0, but can be set to higher numbers to slow down the rate at which
data is read from the disk while checking. This may be useful for
background tasks that doesn't matter if they take a bit longer, as long
as they leave disk I/O time for other processes.</p>
<p><tt class="docutils literal">disk_cache_algorithm</tt> tells the disk I/O thread which cache flush
algorithm to use. The default algorithm is largest_contiguous. This
flushes the entire piece, in the write cache, that was least recently
written to. This is specified by the <tt class="docutils literal"><span class="pre">session_settings::lru</span></tt> enum
value. <tt class="docutils literal"><span class="pre">session_settings::largest_contiguous</span></tt> will flush the largest
sequences of contiguous blocks from the write cache, regarless of the
piece's last use time. <tt class="docutils literal"><span class="pre">session_settings::avoid_readback</span></tt> will prioritize
flushing blocks that will avoid having to read them back in to verify
the hash of the piece once it's done. This is especially useful for high
throughput setups, where reading from the disk is especially expensive.</p>
<p><tt class="docutils literal">read_cache_line_size</tt> is the number of blocks to read into the read
cache when a read cache miss occurs. Setting this to 0 is essentially
the same thing as disabling read cache. The number of blocks read
into the read cache is always capped by the piece boundry.</p>
<p>When a piece in the write cache has <tt class="docutils literal">write_cache_line_size</tt> contiguous
blocks in it, they will be flushed. Setting this to 1 effectively
disables the write cache.</p>
<p><tt class="docutils literal">optimistic_disk_retry</tt> is the number of seconds from a disk write
errors occur on a torrent until libtorrent will take it out of the
upload mode, to test if the error condition has been fixed.</p>
<p>libtorrent will only do this automatically for auto managed torrents.</p>
<p>You can explicitly take a torrent out of upload only mode using
<a class="reference internal" href="#set-upload-mode">set_upload_mode()</a>.</p>
<p><tt class="docutils literal">disable_hash_check</tt> controls if downloaded pieces are verified against
the piece hashes in the torrent file or not. The default is false, i.e.
to verify all downloaded data. It may be useful to turn this off for performance
profiling and simulation scenarios. Do not disable the hash check for regular
bittorrent clients.</p>
<p><tt class="docutils literal">max_suggest_pieces</tt> is the max number of suggested piece indices received
from a peer that's remembered. If a peer floods suggest messages, this limit
prevents libtorrent from using too much RAM. It defaults to 10.</p>
<p>If <tt class="docutils literal">drop_skipped_requests</tt> is set to true (it defaults to false), piece
requests that have been skipped enough times when piece messages
are received, will be considered lost. Requests are considered skipped
when the returned piece messages are re-ordered compared to the order
of the requests. This was an attempt to get out of dead-locks caused by
BitComet peers silently ignoring some requests. It may cause problems
at high rates, and high level of reordering in the uploading peer, that's
why it's disabled by default.</p>
<p><tt class="docutils literal">low_prio_disk</tt> determines if the disk I/O should use a normal
or low priority policy. This defaults to true, which means that
it's low priority by default. Other processes doing disk I/O will
normally take priority in this mode. This is meant to improve the
overall responsiveness of the system while downloading in the
background. For high-performance server setups, this might not
be desirable.</p>
<p><tt class="docutils literal">local_service_announce_interval</tt> is the time between local
network announces for a torrent. By default, when local service
discovery is enabled a torrent announces itself every 5 minutes.
This interval is specified in seconds.</p>
<p><tt class="docutils literal">dht_announce_interval</tt> is the number of seconds between announcing
torrents to the distributed hash table (DHT). This is specified to
be 15 minutes which is its default.</p>
<p><tt class="docutils literal">dht_max_torrents</tt> is the max number of torrents we will track
in the DHT.</p>
<p><tt class="docutils literal">udp_tracker_token_expiry</tt> is the number of seconds libtorrent
will keep UDP tracker connection tokens around for. This is specified
to be 60 seconds, and defaults to that. The higher this value is, the
fewer packets have to be sent to the UDP tracker. In order for higher
values to work, the tracker needs to be configured to match the
expiration time for tokens.</p>
<p><tt class="docutils literal">volatile_read_cache</tt>, if this is set to true, read cache blocks
that are hit by peer read requests are removed from the disk cache
to free up more space. This is useful if you don't expect the disk
cache to create any cache hits from other peers than the one who
triggered the cache line to be read into the cache in the first place.</p>
<p><tt class="docutils literal">guided_read_cache</tt> enables the disk cache to adjust the size
of a cache line generated by peers to depend on the upload rate
you are sending to that peer. The intention is to optimize the RAM
usage of the cache, to read ahead further for peers that you're
sending faster to.</p>
<p><tt class="docutils literal">default_min_cache_age</tt> is the minimum number of seconds any read
cache line is kept in the cache. This defaults to one second but
may be greater if <tt class="docutils literal">guided_read_cache</tt> is enabled. Having a lower
bound on the time a cache line stays in the cache is an attempt
to avoid swapping the same pieces in and out of the cache in case
there is a shortage of spare cache space.</p>
<p><tt class="docutils literal">num_optimistic_unchoke_slots</tt> is the number of optimistic unchoke
slots to use. It defaults to 0, which means automatic. Having a higher
number of optimistic unchoke slots mean you will find the good peers
faster but with the trade-off to use up more bandwidth. When this is
set to 0, libtorrent opens up 20% of your allowed upload slots as
optimistic unchoke slots.</p>
<p><tt class="docutils literal">no_atime_storage</tt> this is a linux-only option and passes in the
<tt class="docutils literal">O_NOATIME</tt> to <tt class="docutils literal">open()</tt> when opening files. This may lead to
some disk performance improvements.</p>
<p><tt class="docutils literal">default_est_reciprocation_rate</tt> is the assumed reciprocation rate
from peers when using the BitTyrant choker. This defaults to 14 kiB/s.
If set too high, you will over-estimate your peers and be more altruistic
while finding the true reciprocation rate, if it's set too low, you'll
be too stingy and waste finding the true reciprocation rate.</p>
<p><tt class="docutils literal">increase_est_reciprocation_rate</tt> specifies how many percent the
extimated reciprocation rate should be increased by each unchoke
interval a peer is still choking us back. This defaults to 20%.
This only applies to the BitTyrant choker.</p>
<p><tt class="docutils literal">decrease_est_reciprocation_rate</tt> specifies how many percent the
estimated reciprocation rate should be decreased by each unchoke
interval a peer unchokes us. This default to 3%.
This only applies to the BitTyrant choker.</p>
<p><tt class="docutils literal">incoming_starts_queued_torrents</tt> defaults to false. If a torrent
has been paused by the auto managed feature in libtorrent, i.e.
the torrent is paused and auto managed, this feature affects whether
or not it is automatically started on an incoming connection. The
main reason to queue torrents, is not to make them unavailable, but
to save on the overhead of announcing to the trackers, the DHT and to
avoid spreading one's unchoke slots too thin. If a peer managed to
find us, even though we're no in the torrent anymore, this setting
can make us start the torrent and serve it.</p>
<p>When <tt class="docutils literal">report_true_downloaded</tt> is true, the <tt class="docutils literal">&amp;downloaded=</tt> argument
sent to trackers will include redundant downloaded bytes. It defaults
to <tt class="docutils literal">false</tt>, which means redundant bytes are not reported to the tracker.</p>
<p><tt class="docutils literal">strict_end_game_mode</tt> defaults to true, and controls when a block
may be requested twice. If this is <tt class="docutils literal">true</tt>, a block may only be requested
twice when there's ay least one request to every piece that's left to
download in the torrent. This may slow down progress on some pieces
sometimes, but it may also avoid downloading a lot of redundant bytes.
If this is <tt class="docutils literal">false</tt>, libtorrent attempts to use each peer connection
to its max, by always requesting something, even if it means requesting
something that has been requested from another peer already.</p>
<p>if <tt class="docutils literal">broadcast_lsd</tt> is set to true, the local peer discovery
(or Local Service Discovery) will not only use IP multicast, but also
broadcast its messages. This can be useful when running on networks
that don't support multicast. Since broadcast messages might be
expensive and disruptive on networks, only every 8th announce uses
broadcast.</p>
<p><tt class="docutils literal">enable_outgoing_utp</tt>, <tt class="docutils literal">enable_incoming_utp</tt>, <tt class="docutils literal">enable_outgoing_tcp</tt>,
<tt class="docutils literal">enable_incoming_tcp</tt> all determines if libtorrent should attempt to make
outgoing connections of the specific type, or allow incoming connection. By
default all of them are enabled.</p>
<p><tt class="docutils literal">ignore_resume_timestamps</tt> determines if the storage, when loading
resume data files, should verify that the file modification time
with the timestamps in the resume data. This defaults to false, which
means timestamps are taken into account, and resume data is less likely
to accepted (torrents are more likely to be fully checked when loaded).
It might be useful to set this to true if your network is faster than your
disk, and it would be faster to redownload potentially missed pieces than
to go through the whole storage to look for them.</p>
<p><tt class="docutils literal">no_recheck_incomplete_resume</tt> determines if the storage should check
the whole files when resume data is incomplete or missing or whether
it should simply assume we don't have any of the data. By default, this
is determined by the existance of any of the files. By setting this setting
to true, the files won't be checked, but will go straight to download
mode.</p>
<p><tt class="docutils literal">anonymous_mode</tt> defaults to false. When set to true, the client tries
to hide its identity to a certain degree. The peer-ID will no longer
include the client's fingerprint. The user-agent will be reset to an
empty string. Trackers will only be used if they are using a proxy
server. The listen sockets are closed, and incoming connections will
only be accepted through a SOCKS5 or I2P proxy (if a peer proxy is set up and
is run on the same machine as the tracker proxy). Since no incoming connections
are accepted, NAT-PMP, UPnP, DHT and local peer discovery are all turned off
when this setting is enabled.</p>
<p>If you're using I2P, it might make sense to enable anonymous mode as well.</p>
<p><tt class="docutils literal">tick_interval</tt> specifies the number of milliseconds between internal
ticks. This is the frequency with which bandwidth quota is distributed to
peers. It should not be more than one second (i.e. 1000 ms). Setting this
to a low value (around 100) means higher resolution bandwidth quota distribution,
setting it to a higher value saves CPU cycles.</p>
<p><tt class="docutils literal">share_mode_target</tt> specifies the target share ratio for share mode torrents.
This defaults to 3, meaning we'll try to upload 3 times as much as we download.
Setting this very high, will make it very conservative and you might end up
not downloading anything ever (and not affecting your share ratio). It does
not make any sense to set this any lower than 2. For instance, if only 3 peers
need to download the rarest piece, it's impossible to download a single piece
and upload it more than 3 times. If the share_mode_target is set to more than 3,
nothing is downloaded.</p>
<p><tt class="docutils literal">upload_rate_limit</tt>, <tt class="docutils literal">download_rate_limit</tt>, <tt class="docutils literal">local_upload_rate_limit</tt>
and <tt class="docutils literal">local_download_rate_limit</tt> sets the session-global limits of upload
and download rate limits, in bytes per second. The local rates refer to peers
on the local network. By default peers on the local network are not rate limited.</p>
<p>These rate limits are only used for local peers (peers within the same subnet as
the client itself) and it is only used when <tt class="docutils literal"><span class="pre">session_settings::ignore_limits_on_local_network</span></tt>
is set to true (which it is by default). These rate limits default to unthrottled,
but can be useful in case you want to treat local peers preferentially, but not
quite unthrottled.</p>
<p>A value of 0 means unlimited.</p>
<p><tt class="docutils literal">dht_upload_rate_limit</tt> sets the rate limit on the DHT. This is specified in
bytes per second and defaults to 4000. For busy boxes with lots of torrents
that requires more DHT traffic, this should be raised.</p>
<p><tt class="docutils literal">unchoke_slots_limit</tt> is the mac number of unchoked peers in the session.</p>
<p>The number of unchoke slots may be ignored depending on what
<tt class="docutils literal">choking_algorithm</tt> is set to.</p>
<p><tt class="docutils literal">half_open_limit</tt> sets the maximum number of half-open connections
libtorrent will have when connecting to peers. A half-open connection is one
where connect() has been called, but the connection still hasn't been established
(nor failed). Windows XP Service Pack 2 sets a default, system wide, limit of
the number of half-open connections to 10. So, this limit can be used to work
nicer together with other network applications on that system. The default is
to have no limit, and passing -1 as the limit, means to have no limit. When
limiting the number of simultaneous connection attempts, peers will be put in
a queue waiting for their turn to get connected.</p>
<p><tt class="docutils literal">connections_limit</tt> sets a global limit on the number of connections
opened. The number of connections is set to a hard minimum of at least two per
torrent, so if you set a too low connections limit, and open too many torrents,
the limit will not be met.</p>
<p><tt class="docutils literal">utp_target_delay</tt> is the target delay for uTP sockets in milliseconds. A high
value will make uTP connections more aggressive and cause longer queues in the upload
bottleneck. It cannot be too low, since the noise in the measurements would cause
it to send too slow. The default is 50 milliseconds.</p>
<p><tt class="docutils literal">utp_gain_factor</tt> is the number of bytes the uTP congestion window can increase
at the most in one RTT. This defaults to 300 bytes. If this is set too high,
the congestion controller reacts too hard to noise and will not be stable, if it's
set too low, it will react slow to congestion and not back off as fast.</p>
<p><tt class="docutils literal">utp_min_timeout</tt> is the shortest allowed uTP socket timeout, specified in milliseconds.
This defaults to 500 milliseconds. The timeout depends on the RTT of the connection, but
is never smaller than this value. A connection times out when every packet in a window
is lost, or when a packet is lost twice in a row (i.e. the resent packet is lost as well).</p>
<p>The shorter the timeout is, the faster the connection will recover from this situation,
assuming the RTT is low enough.</p>
<p><tt class="docutils literal">utp_syn_resends</tt> is the number of SYN packets that are sent (and timed out) before
giving up and closing the socket.</p>
<p><tt class="docutils literal">utp_num_resends</tt> is the number of times a packet is sent (and lossed or timed out)
before giving up and closing the connection.</p>
<p><tt class="docutils literal">utp_connect_timeout</tt> is the number of milliseconds of timeout for the initial SYN
packet for uTP connections. For each timed out packet (in a row), the timeout is doubled.</p>
<p><tt class="docutils literal">utp_dynamic_sock_buf</tt> controls if the uTP socket manager is allowed to increase
the socket buffer if a network interface with a large MTU is used (such as loopback
or ethernet jumbo frames). This defaults to true and might improve uTP throughput.
For RAM constrained systems, disabling this typically saves around 30kB in user space
and probably around 400kB in kernel socket buffers (it adjusts the send and receive
buffer size on the kernel socket, both for IPv4 and IPv6).</p>
<p><tt class="docutils literal">utp_loss_multiplier</tt> controls how the congestion window is changed when a packet
loss is experienced. It's specified as a percentage multiplier for <tt class="docutils literal">cwnd</tt>. By default
it's set to 50 (i.e. cut in half). Do not change this value unless you know what
you're doing. Never set it higher than 100.</p>
<p>The <tt class="docutils literal">mixed_mode_algorithm</tt> determines how to treat TCP connections when there are
uTP connections. Since uTP is designed to yield to TCP, there's an inherent problem
when using swarms that have both TCP and uTP connections. If nothing is done, uTP
connections would often be starved out for bandwidth by the TCP connections. This mode
is <tt class="docutils literal">prefer_tcp</tt>. The <tt class="docutils literal">peer_proportional</tt> mode simply looks at the current throughput
and rate limits all TCP connections to their proportional share based on how many of
the connections are TCP. This works best if uTP connections are not rate limited by
the global rate limiter (which they aren't by default).</p>
<p><tt class="docutils literal">rate_limit_utp</tt> determines if uTP connections should be throttled by the global rate
limiter or not. By default they are.</p>
<p><tt class="docutils literal">listen_queue_size</tt> is the value passed in to listen() for the listen socket.
It is the number of outstanding incoming connections to queue up while we're not
actively waiting for a connection to be accepted. The default is 5 which should
be sufficient for any normal client. If this is a high performance server which
expects to receive a lot of connections, or used in a simulator or test, it
might make sense to raise this number. It will not take affect until listen_on()
is called again (or for the first time).</p>
<p>if <tt class="docutils literal">announce_double_nat</tt> is true, the <tt class="docutils literal">&amp;ip=</tt> argument in tracker requests
(unless otherwise specified) will be set to the intermediate IP address, if the
user is double NATed. If ther user is not double NATed, this option has no affect.</p>
<p><tt class="docutils literal">torrent_connect_boost</tt> is the number of peers to try to connect to immediately
when the first tracker response is received for a torrent. This is a boost to
given to new torrents to accelerate them starting up. The normal connect scheduler
is run once every second, this allows peers to be connected immediately instead
of waiting for the session tick to trigger connections.</p>
<p><tt class="docutils literal">seeding_outgoing_connections</tt> determines if seeding (and finished) torrents
should attempt to make outgoing connections or not. By default this is true. It
may be set to false in very specific applications where the cost of making
outgoing connections is high, and there are no or small benefits of doing so.
For instance, if no nodes are behind a firewall or a NAT, seeds don't need to
make outgoing connections.</p>
<p>if <tt class="docutils literal">no_connect_privileged_ports</tt> is true (which is the default), libtorrent
will not connect to any peers on priviliged ports (&lt;= 1023). This can mitigate
using bittorrent swarms for certain DDoS attacks.</p>
<p><tt class="docutils literal">alert_queue_size</tt> is the maximum number of alerts queued up internally. If
alerts are not popped, the queue will eventually fill up to this level. This
defaults to 1000.</p>
<p><tt class="docutils literal">max_metadata_size</tt> is the maximum allowed size (in bytes) to be received
by the metadata extension, i.e. magnet links. It defaults to 1 MiB.</p>
<p><tt class="docutils literal">smooth_connects</tt> is true by default, which means the number of connection
attempts per second may be limited to below the <tt class="docutils literal">connection_speed</tt>, in case
we're close to bump up against the limit of number of connections. The intention
of this setting is to more evenly distribute our connection attempts over time,
instead of attempting to connectin in batches, and timing them out in batches.</p>
<p><tt class="docutils literal">always_send_user_agent</tt> defaults to false. When set to true, web connections
will include a user-agent with every request, as opposed to just the first
request in a connection.</p>
<p><tt class="docutils literal">apply_ip_filter_to_trackers</tt> defaults to true. It determines whether the
IP filter applies to trackers as well as peers. If this is set to false,
trackers are exempt from the IP filter (if there is one). If no IP filter
is set, this setting is irrelevant.</p>
<p><tt class="docutils literal">read_job_every</tt> is used to avoid starvation of read jobs in the disk I/O
thread. By default, read jobs are deferred, sorted by physical disk location
and serviced once all write jobs have been issued. In scenarios where the
download rate is enough to saturate the disk, there's a risk the read jobs will
never be serviced. With this setting, every <em>x</em> write job, issued in a row, will
instead pick one read job off of the sorted queue, where <em>x</em> is <tt class="docutils literal">read_job_every</tt>.</p>
<p><tt class="docutils literal">use_disk_read_ahead</tt> defaults to true and will attempt to optimize disk reads
by giving the operating system heads up of disk read requests as they are queued
in the disk job queue. This gives a significant performance boost for seeding.</p>
<p><tt class="docutils literal">lock_files</tt> determines whether or not to lock files which libtorrent is downloading
to or seeding from. This is implemented using <tt class="docutils literal">fcntl(F_SETLK)</tt> on unix systems and
by not passing in <tt class="docutils literal">SHARE_READ</tt> and <tt class="docutils literal">SHARE_WRITE</tt> on windows. This might prevent
3rd party processes from corrupting the files under libtorrent's feet.</p>
<p><tt class="docutils literal">ssl_listen</tt> sets the listen port for SSL connections. If this is set to 0,
no SSL listen port is opened. Otherwise a socket is opened on this port. This
setting is only taken into account when opening the regular listen port, and
won't re-open the listen socket simply by changing this setting.</p>
<p>It defaults to port 4433.</p>
<p><tt class="docutils literal">tracker_backoff</tt> determines how aggressively to back off from retrying
failing trackers. This value determines <em>x</em> in the following formula, determining
the number of seconds to wait until the next retry:</p>
<blockquote>
delay = 5 + 5 * x / 100 * fails^2</blockquote>
<p>It defaults to 250.</p>
<p>This setting may be useful to make libtorrent more or less aggressive in hitting
trackers.</p>
<p><tt class="docutils literal">ban_web_seeds</tt> enables banning web seeds. By default, web seeds that send
corrupt data are banned.</p>
<p><tt class="docutils literal">max_http_recv_buffer_size</tt> specifies the max number of bytes to receive into
RAM buffers when downloading stuff over HTTP. Specifically when specifying a
URL to a .torrent file when adding a torrent or when announcing to an HTTP
tracker. The default is 2 MiB.</p>
</div>
</div>
<div class="section" id="pe-settings">
<h1>pe_settings</h1>
<p>The <tt class="docutils literal">pe_settings</tt> structure is used to control the settings related
to peer protocol encryption:</p>
<pre class="literal-block">
struct pe_settings
{
        pe_settings();

        enum enc_policy
        {
                forced,
                enabled,
                disabled
        };

        enum enc_level
        {
                plaintext,
                rc4,
                both
        };

        enc_policy out_enc_policy;
        enc_policy in_enc_policy;
        enc_level allowed_enc_level;
        bool prefer_rc4;
};
</pre>
<p><tt class="docutils literal">in_enc_policy</tt> and <tt class="docutils literal">out_enc_policy</tt> control the settings for incoming
and outgoing connections respectively. The settings for these are:</p>
<blockquote>
<ul class="simple">
<li><tt class="docutils literal">forced</tt> - Only encrypted connections are allowed. Incoming connections
that are not encrypted are closed and if the encrypted outgoing connection
fails, a non-encrypted retry will not be made.</li>
<li><tt class="docutils literal">enabled</tt> - encrypted connections are enabled, but non-encrypted
connections are allowed. An incoming non-encrypted connection will
be accepted, and if an outgoing encrypted connection fails, a non-
encrypted connection will be tried.</li>
<li><tt class="docutils literal">disabled</tt> - only non-encrypted connections are allowed.</li>
</ul>
</blockquote>
<p><tt class="docutils literal">allowed_enc_level</tt> determines the encryption level of the
connections.  This setting will adjust which encryption scheme is
offered to the other peer, as well as which encryption scheme is
selected by the client. The settings are:</p>
<blockquote>
<ul class="simple">
<li><tt class="docutils literal">plaintext</tt> - only the handshake is encrypted, the bulk of the traffic
remains unchanged.</li>
<li><tt class="docutils literal">rc4</tt> - the entire stream is encrypted with RC4</li>
<li><tt class="docutils literal">both</tt> - both RC4 and plaintext connections are allowed.</li>
</ul>
</blockquote>
<p><tt class="docutils literal">prefer_rc4</tt> can be set to true if you want to prefer the RC4 encrypted stream.</p>
</div>
<div class="section" id="proxy-settings">
<h1>proxy_settings</h1>
<p>The <tt class="docutils literal">proxy_settings</tt> structs contains the information needed to
direct certain traffic to a proxy.</p>
<blockquote>
<pre class="literal-block">
struct proxy_settings
{
        proxy_settings();

        std::string hostname;
        int port;

        std::string username;
        std::string password;

        enum proxy_type
        {
                none,
                socks4,
                socks5,
                socks5_pw,
                http,
                http_pw
        };

        proxy_type type;
        bool proxy_hostnames;
        bool proxy_peer_connections;
};
</pre>
</blockquote>
<p><tt class="docutils literal">hostname</tt> is the name or IP of the proxy server. <tt class="docutils literal">port</tt> is the
port number the proxy listens to. If required, <tt class="docutils literal">username</tt> and <tt class="docutils literal">password</tt>
can be set to authenticate with the proxy.</p>
<p>The <tt class="docutils literal">type</tt> tells libtorrent what kind of proxy server it is. The following
options are available:</p>
<blockquote>
<ul class="simple">
<li><tt class="docutils literal">none</tt> - This is the default, no proxy server is used, all other fields
are ignored.</li>
<li><tt class="docutils literal">socks4</tt> - The server is assumed to be a <a class="reference external" href="http://www.ufasoft.com/doc/socks4_protocol.htm">SOCKS4 server</a> that
requires a username.</li>
<li><tt class="docutils literal">socks5</tt> - The server is assumed to be a SOCKS5 server (<a class="reference external" href="http://www.faqs.org/rfcs/rfc1928.html">RFC 1928</a>) that
does not require any authentication. The username and password are ignored.</li>
<li><tt class="docutils literal">socks5_pw</tt> - The server is assumed to be a SOCKS5 server that supports
plain text username and password authentication (<a class="reference external" href="http://www.faqs.org/rfcs/rfc1929.html">RFC 1929</a>). The username
and password specified may be sent to the proxy if it requires.</li>
<li><tt class="docutils literal">http</tt> - The server is assumed to be an HTTP proxy. If the transport used
for the connection is non-HTTP, the server is assumed to support the
<a class="reference external" href="draft-luotonen-web-proxy-tunneling-01.txt">CONNECT</a> method. i.e. for web seeds and HTTP trackers, a plain proxy will
suffice. The proxy is assumed to not require authorization. The username
and password will not be used.</li>
<li><tt class="docutils literal">http_pw</tt> - The server is assumed to be an HTTP proxy that requires
user authorization. The username and password will be sent to the proxy.</li>
</ul>
</blockquote>
<p><tt class="docutils literal">proxy_hostnames</tt> defaults to true. It means that hostnames should be
attempted to be resolved through the proxy instead of using the local DNS
service. This is only supported by SOCKS5 and HTTP.</p>
<p><tt class="docutils literal">proxy_peer_connections</tt> determines whether or not to excempt peer and
web seed connections from using the proxy. This defaults to true, i.e. peer
connections are proxied by default.</p>
</div>
<div class="section" id="ip-filter">
<h1>ip_filter</h1>
<p>The <tt class="docutils literal">ip_filter</tt> class is a set of rules that uniquely categorizes all
ip addresses as allowed or disallowed. The default constructor creates
a single rule that allows all addresses (0.0.0.0 - 255.255.255.255 for
the IPv4 range, and the equivalent range covering all addresses for the
IPv6 range).</p>
<blockquote>
<pre class="literal-block">
template &lt;class Addr&gt;
struct ip_range
{
        Addr first;
        Addr last;
        int flags;
};

class ip_filter
{
public:
        enum access_flags { blocked = 1 };

        ip_filter();
        void add_rule(address first, address last, int flags);
        int access(address const&amp; addr) const;

        typedef boost::tuple&lt;std::vector&lt;ip_range&lt;address_v4&gt; &gt;
                , std::vector&lt;ip_range&lt;address_v6&gt; &gt; &gt; filter_tuple_t;

        filter_tuple_t export_filter() const;
};
</pre>
</blockquote>
<div class="section" id="id8">
<h2>ip_filter()</h2>
<blockquote>
<pre class="literal-block">
ip_filter()
</pre>
</blockquote>
<p>Creates a default filter that doesn't filter any address.</p>
<p>postcondition:
<tt class="docutils literal">access(x) == 0</tt> for every <tt class="docutils literal">x</tt></p>
</div>
<div class="section" id="add-rule">
<h2>add_rule()</h2>
<blockquote>
<pre class="literal-block">
void add_rule(address first, address last, int flags);
</pre>
</blockquote>
<p>Adds a rule to the filter. <tt class="docutils literal">first</tt> and <tt class="docutils literal">last</tt> defines a range of
ip addresses that will be marked with the given flags. The <tt class="docutils literal">flags</tt>
can currently be 0, which means allowed, or <tt class="docutils literal"><span class="pre">ip_filter::blocked</span></tt>, which
means disallowed.</p>
<p>precondition:
<tt class="docutils literal">first.is_v4() == last.is_v4() &amp;&amp; first.is_v6() == last.is_v6()</tt></p>
<p>postcondition:
<tt class="docutils literal">access(x) == flags</tt> for every <tt class="docutils literal">x</tt> in the range [<tt class="docutils literal">first</tt>, <tt class="docutils literal">last</tt>]</p>
<p>This means that in a case of overlapping ranges, the last one applied takes
precedence.</p>
</div>
<div class="section" id="access">
<h2>access()</h2>
<blockquote>
<pre class="literal-block">
int access(address const&amp; addr) const;
</pre>
</blockquote>
<p>Returns the access permissions for the given address (<tt class="docutils literal">addr</tt>). The permission
can currently be 0 or <tt class="docutils literal"><span class="pre">ip_filter::blocked</span></tt>. The complexity of this operation
is O(<tt class="docutils literal">log</tt> n), where n is the minimum number of non-overlapping ranges to describe
the current filter.</p>
</div>
<div class="section" id="export-filter">
<h2>export_filter()</h2>
<blockquote>
<pre class="literal-block">
boost::tuple&lt;std::vector&lt;ip_range&lt;address_v4&gt; &gt;
        , std::vector&lt;ip_range&lt;address_v6&gt; &gt; &gt; export_filter() const;
</pre>
</blockquote>
<p>This function will return the current state of the filter in the minimum number of
ranges possible. They are sorted from ranges in low addresses to high addresses. Each
entry in the returned vector is a range with the access control specified in its
<tt class="docutils literal">flags</tt> field.</p>
<p>The return value is a tuple containing two range-lists. One for IPv4 addresses
and one for IPv6 addresses.</p>
</div>
</div>
<div class="section" id="big-number">
<h1>big_number</h1>
<p>Both the <tt class="docutils literal">peer_id</tt> and <tt class="docutils literal">sha1_hash</tt> types are typedefs of the class
<tt class="docutils literal">big_number</tt>. It represents 20 bytes of data. Its synopsis follows:</p>
<pre class="literal-block">
class big_number
{
public:
        bool operator==(const big_number&amp; n) const;
        bool operator!=(const big_number&amp; n) const;
        bool operator&lt;(const big_number&amp; n) const;

        const unsigned char* begin() const;
        const unsigned char* end() const;

        unsigned char* begin();
        unsigned char* end();
};
</pre>
<p>The iterators gives you access to individual bytes.</p>
</div>
<div class="section" id="bitfield">
<h1>bitfield</h1>
<p>The bitfiled type stores any number of bits as a bitfield in an array.</p>
<pre class="literal-block">
class bitfield
{
        bitfield();
        bitfield(int bits);
        bitfield(int bits, bool val);
        bitfield(char const* bytes, int bits);
        bitfield(bitfield const&amp; rhs);

        void borrow_bytes(char* bytes, int bits);
        ~bitfield();

        void assign(char const* bytes, int bits);

        bool operator[](int index) const;

        bool get_bit(int index) const;

        void clear_bit(int index);
        void set_bit(int index);

        std::size_t size() const;
        bool empty() const;

        char const* bytes() const;

        bitfield&amp; operator=(bitfield const&amp; rhs);

        int count() const;

        typedef const_iterator;
        const_iterator begin() const;
        const_iterator end() const;

        void resize(int bits, bool val);
        void set_all();
        void clear_all();
        void resize(int bits);
};
</pre>
</div>
<div class="section" id="hasher">
<h1>hasher</h1>
<p>This class creates sha1-hashes. Its declaration looks like this:</p>
<pre class="literal-block">
class hasher
{
public:
        hasher();
        hasher(char const* data, unsigned int len);

        void update(char const* data, unsigned int len);
        sha1_hash final();
        void reset();
};
</pre>
<p>You use it by first instantiating it, then call <tt class="docutils literal">update()</tt> to feed it
with data. i.e. you don't have to keep the entire buffer of which you want to
create the hash in memory. You can feed the hasher parts of it at a time. When
You have fed the hasher with all the data, you call <tt class="docutils literal">final()</tt> and it
will return the sha1-hash of the data.</p>
<p>The constructor that takes a <tt class="docutils literal">char const*</tt> and an integer will construct the
sha1 context and feed it the data passed in.</p>
<p>If you want to reuse the hasher object once you have created a hash, you have to
call <tt class="docutils literal">reset()</tt> to reinitialize it.</p>
<p>The sha1-algorithm used was implemented by Steve Reid and released as public domain.
For more info, see <tt class="docutils literal">src/sha1.cpp</tt>.</p>
</div>
<div class="section" id="fingerprint">
<h1>fingerprint</h1>
<p>The fingerprint class represents information about a client and its version. It is used
to encode this information into the client's peer id.</p>
<p>This is the class declaration:</p>
<pre class="literal-block">
struct fingerprint
{
        fingerprint(const char* id_string, int major, int minor
                , int revision, int tag);

        std::string to_string() const;

        char name[2];
        char major_version;
        char minor_version;
        char revision_version;
        char tag_version;

};
</pre>
<p>The constructor takes a <tt class="docutils literal">char const*</tt> that should point to a string constant containing
exactly two characters. These are the characters that should be unique for your client. Make
sure not to clash with anybody else. Here are some taken id's:</p>
<table border="1" class="docutils">
<colgroup>
<col width="30%" />
<col width="70%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">id chars</th>
<th class="head">client</th>
</tr>
</thead>
<tbody valign="top">
<tr><td>'AZ'</td>
<td>Azureus</td>
</tr>
<tr><td>'LT'</td>
<td>libtorrent (default)</td>
</tr>
<tr><td>'BX'</td>
<td>BittorrentX</td>
</tr>
<tr><td>'MT'</td>
<td>Moonlight Torrent</td>
</tr>
<tr><td>'TS'</td>
<td>Torrent Storm</td>
</tr>
<tr><td>'SS'</td>
<td>Swarm Scope</td>
</tr>
<tr><td>'XT'</td>
<td>Xan Torrent</td>
</tr>
</tbody>
</table>
<p>There's currently an informal directory of client id's <a class="reference external" href="http://wiki.theory.org/BitTorrentSpecification#peer_id">here</a>.</p>
<p>The <tt class="docutils literal">major</tt>, <tt class="docutils literal">minor</tt>, <tt class="docutils literal">revision</tt> and <tt class="docutils literal">tag</tt> parameters are used to identify the
version of your client. All these numbers must be within the range [0, 9].</p>
<p><tt class="docutils literal">to_string()</tt> will generate the actual string put in the peer-id, and return it.</p>
</div>
<div class="section" id="upnp-and-nat-pmp">
<h1>UPnP and NAT-PMP</h1>
<p>The <tt class="docutils literal">upnp</tt> and <tt class="docutils literal">natpmp</tt> classes contains the state for all UPnP and NAT-PMP mappings,
by default 1 or two mappings are made by libtorrent, one for the listen port and one
for the DHT port (UDP).</p>
<pre class="literal-block">
class upnp
{
public:

        enum protocol_type { none = 0, udp = 1, tcp = 2 };
        int add_mapping(protocol_type p, int external_port, int local_port);
        void delete_mapping(int mapping_index);

        void discover_device();
        void close();

        std::string router_model();
};

class natpmp
{
public:

        enum protocol_type { none = 0, udp = 1, tcp = 2 };
        int add_mapping(protocol_type p, int external_port, int local_port);
        void delete_mapping(int mapping_index);

        void close();
        void rebind(address const&amp; listen_interface);
};
</pre>
<p><tt class="docutils literal">discover_device()</tt>, <tt class="docutils literal">close()</tt> and <tt class="docutils literal">rebind()</tt> are for internal uses and should
not be called directly by clients.</p>
<div class="section" id="add-mapping">
<h2>add_mapping()</h2>
<blockquote>
<pre class="literal-block">
int add_mapping(protocol_type p, int external_port, int local_port);
</pre>
</blockquote>
<p>Attempts to add a port mapping for the specified protocol. Valid protocols are
<tt class="docutils literal"><span class="pre">upnp::tcp</span></tt> and <tt class="docutils literal"><span class="pre">upnp::udp</span></tt> for the UPnP class and <tt class="docutils literal"><span class="pre">natpmp::tcp</span></tt> and
<tt class="docutils literal"><span class="pre">natpmp::udp</span></tt> for the NAT-PMP class.</p>
<p><tt class="docutils literal">external_port</tt> is the port on the external address that will be mapped. This
is a hint, you are not guaranteed that this port will be available, and it may
end up being something else. In the <a class="reference internal" href="#portmap-alert">portmap_alert</a> notification, the actual
external port is reported.</p>
<p><tt class="docutils literal">local_port</tt> is the port in the local machine that the mapping should forward
to.</p>
<p>The return value is an index that identifies this port mapping. This is used
to refer to mappings that fails or succeeds in the <a class="reference internal" href="#portmap-error-alert">portmap_error_alert</a> and
<a class="reference internal" href="#portmap-alert">portmap_alert</a> respectively. If The mapping fails immediately, the return value
is -1, which means failure. There will not be any error alert notification for
mappings that fail with a -1 return value.</p>
</div>
<div class="section" id="delete-mapping">
<h2>delete_mapping()</h2>
<blockquote>
<pre class="literal-block">
void delete_mapping(int mapping_index);
</pre>
</blockquote>
<p>This function removes a port mapping. <tt class="docutils literal">mapping_index</tt> is the index that refers
to the mapping you want to remove, which was returned from <a class="reference internal" href="#add-mapping">add_mapping()</a>.</p>
</div>
<div class="section" id="router-model">
<h2>router_model()</h2>
<blockquote>
<pre class="literal-block">
std::string router_model();
</pre>
</blockquote>
<p>This is only available for UPnP routers. If the model is advertized by
the router, it can be queried through this function.</p>
</div>
</div>
<div class="section" id="free-functions">
<h1>free functions</h1>
<div class="section" id="identify-client">
<h2>identify_client()</h2>
<blockquote>
<pre class="literal-block">
std::string identify_client(peer_id const&amp; id);
</pre>
</blockquote>
<p>This function is declared in the header <tt class="docutils literal">&lt;libtorrent/identify_client.hpp&gt;</tt>. It can can be used
to extract a string describing a client version from its peer-id. It will recognize most clients
that have this kind of identification in the peer-id.</p>
</div>
<div class="section" id="client-fingerprint">
<h2>client_fingerprint()</h2>
<blockquote>
<pre class="literal-block">
boost::optional&lt;fingerprint&gt; client_fingerprint(peer_id const&amp; p);
</pre>
</blockquote>
<p>Returns an optional fingerprint if any can be identified from the peer id. This can be used
to automate the identification of clients. It will not be able to identify peers with non-
standard encodings. Only Azureus style, Shadow's style and Mainline style. This function is
declared in the header <tt class="docutils literal">&lt;libtorrent/identify_client.hpp&gt;</tt>.</p>
</div>
<div class="section" id="lazy-bdecode">
<h2>lazy_bdecode()</h2>
<blockquote>
<pre class="literal-block">
int lazy_bdecode(char const* start, char const* end, lazy_entry&amp; ret
        , error_code&amp; ec, int* error_pos = 0, int depth_limit = 1000
        , int item_limit = 1000000);
</pre>
</blockquote>
<p>This function decodes <a class="reference external" href="http://wiki.theory.org/index.php/BitTorrentSpecification">bencoded</a> data.</p>
<p>Whenever possible, <tt class="docutils literal">lazy_bdecode()</tt> should be preferred over <tt class="docutils literal">bdecode()</tt>.
It is more efficient and more secure. It supports having constraints on the
amount of memory is consumed by the parser.</p>
<p><em>lazy</em> refers to the fact that it doesn't copy any actual data out of the
bencoded buffer. It builds a tree of <tt class="docutils literal">lazy_entry</tt> which has pointers into
the bencoded buffer. This makes it very fast and efficient. On top of that,
it is not recursive, which saves a lot of stack space when parsing deeply
nested trees. However, in order to protect against potential attacks, the
<tt class="docutils literal">depth_limit</tt> and <tt class="docutils literal">item_limit</tt> control how many levels deep the tree is
allowed to get. With recursive parser, a few thousand levels would be enough
to exhaust the threads stack and terminate the process. The <tt class="docutils literal">item_limit</tt>
protects against very large structures, not necessarily deep. Each bencoded
item in the structure causes the parser to allocate some amount of memory,
this memory is constant regardless of how much data actually is stored in
the item. One potential attack is to create a bencoded list of hundreds of
thousands empty strings, which would cause the parser to allocate a significant
amount of memory, perhaps more than is available on the machine, and effectively
provide a denial of service. The default item limit is set as a reasonable
upper limit for desktop computers. Very few torrents have more items in them.
The limit corresponds to about 25 MB, which might be a bit much for embedded
systems.</p>
<p><tt class="docutils literal">start</tt> and <tt class="docutils literal">end</tt> defines the bencoded buffer to be decoded. <tt class="docutils literal">ret</tt> is
the <tt class="docutils literal">lazy_entry</tt> which is filled in with the whole decoded tree. <tt class="docutils literal">ec</tt>
is a reference to an <tt class="docutils literal">error_code</tt> which is set to describe the error encountered
in case the function fails. <tt class="docutils literal">error_pos</tt> is an optional pointer to an int,
which will be set to the byte offset into the buffer where an error occurred,
in case the function fails.</p>
</div>
<div class="section" id="bdecode-bencode">
<h2>bdecode() bencode()</h2>
<blockquote>
<pre class="literal-block">
template&lt;class InIt&gt; entry bdecode(InIt start, InIt end);
template&lt;class OutIt&gt; void bencode(OutIt out, const entry&amp; e);
</pre>
</blockquote>
<p>These functions will encode data to <a class="reference external" href="http://wiki.theory.org/index.php/BitTorrentSpecification">bencoded</a> or decode <a class="reference external" href="http://wiki.theory.org/index.php/BitTorrentSpecification">bencoded</a> data.</p>
<p>If possible, <a class="reference internal" href="#lazy-bdecode">lazy_bdecode()</a> should be preferred over <tt class="docutils literal">bdecode()</tt>.</p>
<p>The <a class="reference internal" href="#entry">entry</a> class is the internal representation of the bencoded data
and it can be used to retrieve information, an <a class="reference internal" href="#entry">entry</a> can also be build by
the program and given to <tt class="docutils literal">bencode()</tt> to encode it into the <tt class="docutils literal">OutIt</tt>
iterator.</p>
<p>The <tt class="docutils literal">OutIt</tt> and <tt class="docutils literal">InIt</tt> are iterators
(<a class="reference external" href="http://www.sgi.com/tech/stl/InputIterator.html">InputIterator</a> and <a class="reference external" href="http://www.sgi.com/tech/stl/OutputIterator.html">OutputIterator</a> respectively). They
are templates and are usually instantiated as <a class="reference external" href="http://www.sgi.com/tech/stl/ostream_iterator.html">ostream_iterator</a>,
<a class="reference external" href="http://www.sgi.com/tech/stl/back_insert_iterator.html">back_insert_iterator</a> or <a class="reference external" href="http://www.sgi.com/tech/stl/istream_iterator.html">istream_iterator</a>. These
functions will assume that the iterator refers to a character
(<tt class="docutils literal">char</tt>). So, if you want to encode entry <tt class="docutils literal">e</tt> into a buffer
in memory, you can do it like this:</p>
<pre class="literal-block">
std::vector&lt;char&gt; buffer;
bencode(std::back_inserter(buf), e);
</pre>
<p>If you want to decode a torrent file from a buffer in memory, you can do it like this:</p>
<pre class="literal-block">
std::vector&lt;char&gt; buffer;
// ...
entry e = bdecode(buf.begin(), buf.end());
</pre>
<p>Or, if you have a raw char buffer:</p>
<pre class="literal-block">
const char* buf;
// ...
entry e = bdecode(buf, buf + data_size);
</pre>
<p>Now we just need to know how to retrieve information from the <a class="reference internal" href="#entry">entry</a>.</p>
<p>If <tt class="docutils literal">bdecode()</tt> encounters invalid encoded data in the range given to it
it will throw <a class="reference internal" href="#libtorrent-exception">libtorrent_exception</a>.</p>
</div>
<div class="section" id="add-magnet-uri">
<h2>add_magnet_uri()</h2>
<p><em>deprecated</em></p>
<blockquote>
<pre class="literal-block">
torrent_handle add_magnet_uri(session&amp; ses, std::string const&amp; uri
        add_torrent_params p);
torrent_handle add_magnet_uri(session&amp; ses, std::string const&amp; uri
        add_torrent_params p, error_code&amp; ec);
</pre>
</blockquote>
<p>This function parses the magnet URI (<tt class="docutils literal">uri</tt>) as a bittorrent magnet link,
and adds the torrent to the specified session (<tt class="docutils literal">ses</tt>). It returns the
handle to the newly added torrent, or an invalid handle in case parsing
failed. To control some initial settings of the torrent, sepcify those in
the <tt class="docutils literal">add_torrent_params</tt>, <tt class="docutils literal">p</tt>. See <a class="reference internal" href="#async-add-torrent-add-torrent">async_add_torrent() add_torrent()</a>.</p>
<p>The overload that does not take an <tt class="docutils literal">error_code</tt> throws an exception on
error and is not available when building without exception support.</p>
<p>A simpler way to add a magnet link to a session is to pass in the
link through <tt class="docutils literal"><span class="pre">add_torrent_params::url</span></tt> argument to <tt class="docutils literal"><span class="pre">session::add_torrent()</span></tt>.</p>
<p>For more information about magnet links, see <a class="reference internal" href="#magnet-links">magnet links</a>.</p>
</div>
<div class="section" id="parse-magnet-uri">
<h2>parse_magnet_uri()</h2>
<blockquote>
<pre class="literal-block">
void parse_magnet_uri(std::string const&amp; uri, add_torrent_params&amp; p, error_code&amp; ec);
</pre>
</blockquote>
<p>This function parses out information from the magnet link and populates the
<tt class="docutils literal">add_torrent_params</tt> object.</p>
</div>
<div class="section" id="make-magnet-uri">
<h2>make_magnet_uri()</h2>
<blockquote>
<pre class="literal-block">
std::string make_magnet_uri(torrent_handle const&amp; handle);
</pre>
</blockquote>
<p>Generates a magnet URI from the specified torrent. If the torrent
handle is invalid, an empty string is returned.</p>
<p>For more information about magnet links, see <a class="reference internal" href="#magnet-links">magnet links</a>.</p>
</div>
</div>
<div class="section" id="alerts">
<h1>alerts</h1>
<p>The <tt class="docutils literal">pop_alert()</tt> function on session is the interface for retrieving
alerts, warnings, messages and errors from libtorrent. If no alerts have
been posted by libtorrent <tt class="docutils literal">pop_alert()</tt> will return a default initialized
<tt class="docutils literal">auto_ptr</tt> object. If there is an alert in libtorrent's queue, the alert
from the front of the queue is popped and returned.
You can then use the alert object and query</p>
<p>By default, only errors are reported. <a class="reference internal" href="#set-alert-mask">set_alert_mask()</a> can be
used to specify which kinds of events should be reported. The alert mask
is a bitmask with the following bits:</p>
<table border="1" class="docutils">
<colgroup>
<col width="32%" />
<col width="68%" />
</colgroup>
<tbody valign="top">
<tr><td><tt class="docutils literal">error_notification</tt></td>
<td><p class="first">Enables alerts that report an error. This includes:</p>
<ul class="last simple">
<li>tracker errors</li>
<li>tracker warnings</li>
<li>file errors</li>
<li>resume data failures</li>
<li>web seed errors</li>
<li>.torrent files errors</li>
<li>listen socket errors</li>
<li>port mapping errors</li>
</ul>
</td>
</tr>
<tr><td><tt class="docutils literal">peer_notification</tt></td>
<td>Enables alerts when peers send invalid requests, get banned or
snubbed.</td>
</tr>
<tr><td><tt class="docutils literal">port_mapping_notification</tt></td>
<td>Enables alerts for port mapping events. For NAT-PMP and UPnP.</td>
</tr>
<tr><td><tt class="docutils literal">storage_notification</tt></td>
<td>Enables alerts for events related to the storage. File errors and
synchronization events for moving the storage, renaming files etc.</td>
</tr>
<tr><td><tt class="docutils literal">tracker_notification</tt></td>
<td>Enables all tracker events. Includes announcing to trackers,
receiving responses, warnings and errors.</td>
</tr>
<tr><td><tt class="docutils literal">debug_notification</tt></td>
<td>Low level alerts for when peers are connected and disconnected.</td>
</tr>
<tr><td><tt class="docutils literal">status_notification</tt></td>
<td>Enables alerts for when a torrent or the session changes state.</td>
</tr>
<tr><td><tt class="docutils literal">progress_notification</tt></td>
<td>Alerts for when blocks are requested and completed. Also when
pieces are completed.</td>
</tr>
<tr><td><tt class="docutils literal">ip_block_notification</tt></td>
<td>Alerts when a peer is blocked by the ip blocker or port blocker.</td>
</tr>
<tr><td><tt class="docutils literal">performance_warning</tt></td>
<td>Alerts when some limit is reached that might limit the download
or upload rate.</td>
</tr>
<tr><td><tt class="docutils literal">stats_notification</tt></td>
<td>If you enable these alerts, you will receive a <tt class="docutils literal">stats_alert</tt>
approximately once every second, for every active torrent.
These alerts contain all statistics counters for the interval since
the lasts stats alert.</td>
</tr>
<tr><td><tt class="docutils literal">dht_notification</tt></td>
<td>Alerts on events in the DHT node. For incoming searches or
bootstrapping being done etc.</td>
</tr>
<tr><td><tt class="docutils literal">rss_notification</tt></td>
<td>Alerts on RSS related events, like feeds being updated, feed error
conditions and successful RSS feed updates. Enabling this categoty
will make you receive <tt class="docutils literal">rss_alert</tt> alerts.</td>
</tr>
<tr><td><tt class="docutils literal">all_categories</tt></td>
<td>The full bitmask, representing all available categories.</td>
</tr>
</tbody>
</table>
<p>Every alert belongs to one or more category. There is a small cost involved in posting alerts. Only
alerts that belong to an enabled category are posted. Setting the alert bitmask to 0 will disable
all alerts</p>
<p>When you get an alert, you can use <tt class="docutils literal">alert_cast&lt;&gt;</tt> to attempt to cast the pointer to a
more specific alert type, to be queried for more information about the alert. <tt class="docutils literal">alert_cast</tt>
has the followinf signature:</p>
<pre class="literal-block">
template &lt;T&gt; T* alert_cast(alert* a);
template &lt;T&gt; T const* alert_cast(alert const* a);
</pre>
<p>You can also use a <a class="reference internal" href="#alert-dispatcher">alert dispatcher</a> mechanism that's available in libtorrent.</p>
<p>All alert types are defined in the <tt class="docutils literal">&lt;libtorrent/alert_types.hpp&gt;</tt> header file.</p>
<p>The <tt class="docutils literal">alert</tt> class is the base class that specific messages are derived from. This
is its synopsis:</p>
<pre class="literal-block">
class alert
{
public:

        enum category_t
        {
                error_notification = <em>implementation defined</em>,
                peer_notification = <em>implementation defined</em>,
                port_mapping_notification = <em>implementation defined</em>,
                storage_notification = <em>implementation defined</em>,
                tracker_notification = <em>implementation defined</em>,
                debug_notification = <em>implementation defined</em>,
                status_notification = <em>implementation defined</em>,
                progress_notification = <em>implementation defined</em>,
                ip_block_notification = <em>implementation defined</em>,
                performance_warning = <em>implementation defined</em>,
                dht_notification = <em>implementation defined</em>,
                stats_notification = <em>implementation defined</em>,

                all_categories = <em>implementation defined</em>
        };

        ptime timestamp() const;

        virtual ~alert();

        virtual int type() const = 0;
        virtual std::string message() const = 0;
        virtual char const* what() const = 0;
        virtual int category() const = 0;
        virtual bool discardable() const;
        virtual std::auto_ptr&lt;alert&gt; clone() const = 0;
};
</pre>
<p><tt class="docutils literal">type()</tt> returns an integer that is unique to this alert type. It can be
compared against a specific alert by querying a static constant called <tt class="docutils literal">alert_type</tt>
in the alert. It can be used to determine the run-time type of an alert* in
order to cast to that alert type and access specific members.</p>
<p>e.g:</p>
<pre class="literal-block">
std::auto_ptr&lt;alert&gt; a = ses.pop_alert();
switch (a-&gt;type())
{
        case read_piece_alert::alert_type:
        {
                read_piece_alert* p = (read_piece_alert*)a.get();
                // use p
                break;
        }
        case file_renamed_alert::alert_type:
        {
                // etc...
        }
}
</pre>
<p><tt class="docutils literal">what()</tt> returns a string literal describing the type of the alert. It does
not include any information that might be bundled with the alert.</p>
<p><tt class="docutils literal">category()</tt> returns a bitmask specifying which categories this alert belong to.</p>
<p><tt class="docutils literal">clone()</tt> returns a pointer to a copy of the alert.</p>
<p><tt class="docutils literal">discardable()</tt> determines whether or not an alert is allowed to be discarded
when the alert queue is full. There are a few alerts which may not be discared,
since they would break the user contract, such as <tt class="docutils literal">save_resume_data_alert</tt>.</p>
<p><tt class="docutils literal">message()</tt> generate a string describing the alert and the information bundled
with it. This is mainly intended for debug and development use. It is not suitable
to use this for applications that may be localized. Instead, handle each alert
type individually and extract and render the information from the alert depending
on the locale.</p>
<p>There's another alert base class that most alerts derives from, all the
alerts that are generated for a specific torrent are derived from:</p>
<pre class="literal-block">
struct torrent_alert: alert
{
        // ...
        torrent_handle handle;
};
</pre>
<p>There's also a base class for all alerts referring to tracker events:</p>
<pre class="literal-block">
struct tracker_alert: torrent_alert
{
        // ...
        std::string url;
};
</pre>
<p>The specific alerts are:</p>
<div class="section" id="torrent-added-alert">
<h2>torrent_added_alert</h2>
<p>The <tt class="docutils literal">torrent_added_alert</tt> is posted once every time a torrent is successfully
added. It doesn't contain any members of its own, but inherits the torrent handle
from its base class.
It's posted when the <tt class="docutils literal">status_notification</tt> bit is set in the alert mask.</p>
<pre class="literal-block">
struct torrent_added_alert: torrent_alert
{
        // ...
};
</pre>
</div>
<div class="section" id="add-torrent-alert">
<h2>add_torrent_alert</h2>
<p>This alert is always posted when a torrent was attempted to be added
and contains the return status of the add operation. The torrent handle of the new
torrent can be found in the base class' <tt class="docutils literal">handle</tt> member. If adding
the torrent failed, <tt class="docutils literal">error</tt> contains the error code.</p>
<pre class="literal-block">
struct add_torrent_alert: torrent_alert
{
        // ...
        add_torrent_params params;
        error_code error;
};
</pre>
<p><tt class="docutils literal">params</tt> is a copy of the parameters used when adding the torrent, it can be used
to identify which invocation to <tt class="docutils literal">async_add_torrent()</tt> caused this alert.</p>
<p><tt class="docutils literal">error</tt> is set to the error, if one occurred while adding the torrent.</p>
</div>
<div class="section" id="torrent-removed-alert">
<h2>torrent_removed_alert</h2>
<p>The <tt class="docutils literal">torrent_removed_alert</tt> is posted whenever a torrent is removed. Since
the torrent handle in its baseclass will always be invalid (since the torrent
is already removed) it has the info hash as a member, to identify it.
It's posted when the <tt class="docutils literal">status_notification</tt> bit is set in the alert mask.</p>
<p>Even though the <tt class="docutils literal">handle</tt> member doesn't point to an existing torrent anymore,
it is still useful for comparing to other handles, which may also no
longer point to existing torrents, but to the same non-existing torrents.</p>
<p>The <tt class="docutils literal">torrent_handle</tt> acts as a <tt class="docutils literal">weak_ptr</tt>, even though its object no
longer exists, it can still compare equal to another weak pointer which
points to the same non-existent object.</p>
<pre class="literal-block">
struct torrent_removed_alert: torrent_alert
{
        // ...
        sha1_hash info_hash;
};
</pre>
</div>
<div class="section" id="read-piece-alert">
<h2>read_piece_alert</h2>
<p>This alert is posted when the asynchronous read operation initiated by
a call to <a class="reference internal" href="#read-piece">read_piece()</a> is completed. If the read failed, the torrent
is paused and an error state is set and the buffer member of the alert
is 0. If successful, <tt class="docutils literal">buffer</tt> points to a buffer containing all the data
of the piece. <tt class="docutils literal">piece</tt> is the piece index that was read. <tt class="docutils literal">size</tt> is the
number of bytes that was read.</p>
<pre class="literal-block">
struct read_piece_alert: torrent_alert
{
        // ...
        boost::shared_ptr&lt;char&gt; buffer;
        int piece;
        int size;
};
</pre>
</div>
<div class="section" id="external-ip-alert">
<h2>external_ip_alert</h2>
<p>Whenever libtorrent learns about the machines external IP, this alert is
generated. The external IP address can be acquired from the tracker (if it
supports that) or from peers that supports the extension protocol.
The address can be accessed through the <tt class="docutils literal">external_address</tt> member.</p>
<pre class="literal-block">
struct external_ip_alert: alert
{
        // ...
        address external_address;
};
</pre>
</div>
<div class="section" id="listen-failed-alert">
<h2>listen_failed_alert</h2>
<p>This alert is generated when none of the ports, given in the port range, to
<a class="reference internal" href="#session">session</a> can be opened for listening. The <tt class="docutils literal">endpoint</tt> member is the
interface and port that failed, <tt class="docutils literal">error</tt> is the error code describing
the failure.</p>
<p>libtorrent may sometimes try to listen on port 0, if all other ports failed.
Port 0 asks the operating system to pick a port that's free). If that fails
you may see a <a class="reference internal" href="#listen-failed-alert">listen_failed_alert</a> with port 0 even if you didn't ask to
listen on it.</p>
<pre class="literal-block">
struct listen_failed_alert: alert
{
        // ...
        tcp::endpoint endpoint;
        error_code error;
};
</pre>
</div>
<div class="section" id="listen-succeeded-alert">
<h2>listen_succeeded_alert</h2>
<p>This alert is posted when the listen port succeeds to be opened on a
particular interface. <tt class="docutils literal">endpoint</tt> is the endpoint that successfully
was opened for listening.</p>
<pre class="literal-block">
struct listen_succeeded_alert: alert
{
        // ...
        tcp::endpoint endpoint;
};
</pre>
</div>
<div class="section" id="portmap-error-alert">
<h2>portmap_error_alert</h2>
<p>This alert is generated when a NAT router was successfully found but some
part of the port mapping request failed. It contains a text message that
may help the user figure out what is wrong. This alert is not generated in
case it appears the client is not running on a NAT:ed network or if it
appears there is no NAT router that can be remote controlled to add port
mappings.</p>
<p><tt class="docutils literal">mapping</tt> refers to the mapping index of the port map that failed, i.e.
the index returned from <a class="reference internal" href="#add-mapping">add_mapping()</a>.</p>
<p><tt class="docutils literal">map_type</tt> is 0 for NAT-PMP and 1 for UPnP.</p>
<p><tt class="docutils literal">error</tt> tells you what failed.</p>
<pre class="literal-block">
struct portmap_error_alert: alert
{
        // ...
        int mapping;
        int type;
        error_code error;
};
</pre>
</div>
<div class="section" id="portmap-alert">
<h2>portmap_alert</h2>
<p>This alert is generated when a NAT router was successfully found and
a port was successfully mapped on it. On a NAT:ed network with a NAT-PMP
capable router, this is typically generated once when mapping the TCP
port and, if DHT is enabled, when the UDP port is mapped.</p>
<p><tt class="docutils literal">mapping</tt> refers to the mapping index of the port map that failed, i.e.
the index returned from <a class="reference internal" href="#add-mapping">add_mapping()</a>.</p>
<p><tt class="docutils literal">external_port</tt> is the external port allocated for the mapping.</p>
<p><tt class="docutils literal">type</tt> is 0 for NAT-PMP and 1 for UPnP.</p>
<pre class="literal-block">
struct portmap_alert: alert
{
        // ...
        int mapping;
        int external_port;
        int map_type;
};
</pre>
</div>
<div class="section" id="portmap-log-alert">
<h2>portmap_log_alert</h2>
<p>This alert is generated to log informational events related to either
UPnP or NAT-PMP. They contain a log line and the type (0 = NAT-PMP
and 1 = UPnP). Displaying these messages to an end user is only useful
for debugging the UPnP or NAT-PMP implementation.</p>
<pre class="literal-block">
struct portmap_log_alert: alert
{
        //...
        int map_type;
        std::string msg;
};
</pre>
</div>
<div class="section" id="file-error-alert">
<h2>file_error_alert</h2>
<p>If the storage fails to read or write files that it needs access to, this alert is
generated and the torrent is paused.</p>
<p><tt class="docutils literal">file</tt> is the path to the file that was accessed when the error occurred.</p>
<p><tt class="docutils literal">error</tt> is the error code describing the error.</p>
<pre class="literal-block">
struct file_error_alert: torrent_alert
{
        // ...
        std::string file;
        error_code error;
};
</pre>
</div>
<div class="section" id="torrent-error-alert">
<h2>torrent_error_alert</h2>
<p>This is posted whenever a torrent is transitioned into the error state.</p>
<pre class="literal-block">
struct torrent_error_alert: torrent_alert
{
        // ...
        error_code error;
};
</pre>
<p>The <tt class="docutils literal">error</tt> specifies which error the torrent encountered.</p>
</div>
<div class="section" id="file-renamed-alert">
<h2>file_renamed_alert</h2>
<p>This is posted as a response to a <tt class="docutils literal"><span class="pre">torrent_handle::rename_file</span></tt> call, if the rename
operation succeeds.</p>
<pre class="literal-block">
struct file_renamed_alert: torrent_alert
{
        // ...
        std::string name;
        int index;
};
</pre>
<p>The <tt class="docutils literal">index</tt> member refers to the index of the file that was renamed,
<tt class="docutils literal">name</tt> is the new name of the file.</p>
</div>
<div class="section" id="file-rename-failed-alert">
<h2>file_rename_failed_alert</h2>
<p>This is posted as a response to a <tt class="docutils literal"><span class="pre">torrent_handle::rename_file</span></tt> call, if the rename
operation failed.</p>
<pre class="literal-block">
struct file_rename_failed_alert: torrent_alert
{
        // ...
        int index;
        error_code error;
};
</pre>
<p>The <tt class="docutils literal">index</tt> member refers to the index of the file that was supposed to be renamed,
<tt class="docutils literal">error</tt> is the error code returned from the filesystem.</p>
</div>
<div class="section" id="tracker-announce-alert">
<h2>tracker_announce_alert</h2>
<p>This alert is generated each time a tracker announce is sent (or attempted to be sent).
There are no extra data members in this alert. The url can be found in the base class
however.</p>
<pre class="literal-block">
struct tracker_announce_alert: tracker_alert
{
        // ...
        int event;
};
</pre>
<p>Event specifies what event was sent to the tracker. It is defined as:</p>
<ol class="arabic simple" start="0">
<li>None</li>
<li>Completed</li>
<li>Started</li>
<li>Stopped</li>
</ol>
</div>
<div class="section" id="tracker-error-alert">
<h2>tracker_error_alert</h2>
<p>This alert is generated on tracker time outs, premature disconnects, invalid response or
a HTTP response other than &quot;200 OK&quot;. From the alert you can get the handle to the torrent
the tracker belongs to.</p>
<p>The <tt class="docutils literal">times_in_row</tt> member says how many times in a row this tracker has failed.
<tt class="docutils literal">status_code</tt> is the code returned from the HTTP server. 401 means the tracker needs
authentication, 404 means not found etc. If the tracker timed out, the code will be set
to 0.</p>
<pre class="literal-block">
struct tracker_error_alert: tracker_alert
{
        // ...
        int times_in_row;
        int status_code;
};
</pre>
</div>
<div class="section" id="tracker-reply-alert">
<h2>tracker_reply_alert</h2>
<p>This alert is only for informational purpose. It is generated when a tracker announce
succeeds. It is generated regardless what kind of tracker was used, be it UDP, HTTP or
the DHT.</p>
<pre class="literal-block">
struct tracker_reply_alert: tracker_alert
{
        // ...
        int num_peers;
};
</pre>
<p>The <tt class="docutils literal">num_peers</tt> tells how many peers were returned from the tracker. This is
not necessarily all new peers, some of them may already be connected.</p>
</div>
<div class="section" id="tracker-warning-alert">
<h2>tracker_warning_alert</h2>
<p>This alert is triggered if the tracker reply contains a warning field. Usually this
means that the tracker announce was successful, but the tracker has a message to
the client. The <tt class="docutils literal">msg</tt> string in the alert contains the warning message from
the tracker.</p>
<pre class="literal-block">
struct tracker_warning_alert: tracker_alert
{
        // ...
        std::string msg;
};
</pre>
</div>
<div class="section" id="scrape-reply-alert">
<h2>scrape_reply_alert</h2>
<p>This alert is generated when a scrape request succeeds. <tt class="docutils literal">incomplete</tt>
and <tt class="docutils literal">complete</tt> is the data returned in the scrape response. These numbers
may be -1 if the reponse was malformed.</p>
<pre class="literal-block">
struct scrape_reply_alert: tracker_alert
{
        // ...
        int incomplete;
        int complete;
};
</pre>
</div>
<div class="section" id="scrape-failed-alert">
<h2>scrape_failed_alert</h2>
<p>If a scrape request fails, this alert is generated. This might be due
to the tracker timing out, refusing connection or returning an http response
code indicating an error. <tt class="docutils literal">msg</tt> contains a message describing the error.</p>
<pre class="literal-block">
struct scrape_failed_alert: tracker_alert
{
        // ...
        std::string msg;
};
</pre>
</div>
<div class="section" id="url-seed-alert">
<h2>url_seed_alert</h2>
<p>This alert is generated when a HTTP seed name lookup fails.</p>
<p>It contains <tt class="docutils literal">url</tt> to the HTTP seed that failed along with an error message.</p>
<pre class="literal-block">
struct url_seed_alert: torrent_alert
{
        // ...
        std::string url;
};
</pre>
</div>
<div class="section" id="hash-failed-alert">
<h2>hash_failed_alert</h2>
<p>This alert is generated when a finished piece fails its hash check. You can get the handle
to the torrent which got the failed piece and the index of the piece itself from the alert.</p>
<pre class="literal-block">
struct hash_failed_alert: torrent_alert
{
        // ...
        int piece_index;
};
</pre>
</div>
<div class="section" id="peer-alert">
<h2>peer_alert</h2>
<p>The peer alert is a base class for alerts that refer to a specific peer. It includes all
the information to identify the peer. i.e. <tt class="docutils literal">ip</tt> and <tt class="docutils literal"><span class="pre">peer-id</span></tt>.</p>
<pre class="literal-block">
struct peer_alert: torrent_alert
{
        // ...
        tcp::endpoint ip;
        peer_id pid;
};
</pre>
</div>
<div class="section" id="peer-connect-alert">
<h2>peer_connect_alert</h2>
<p>This alert is posted every time an outgoing peer connect attempts succeeds.</p>
<pre class="literal-block">
struct peer_connect_alert: peer_alert
{
        // ...
};
</pre>
</div>
<div class="section" id="peer-ban-alert">
<h2>peer_ban_alert</h2>
<p>This alert is generated when a peer is banned because it has sent too many corrupt pieces
to us. <tt class="docutils literal">ip</tt> is the endpoint to the peer that was banned.</p>
<pre class="literal-block">
struct peer_ban_alert: peer_alert
{
        // ...
};
</pre>
</div>
<div class="section" id="peer-snubbed-alert">
<h2>peer_snubbed_alert</h2>
<p>This alert is generated when a peer is snubbed, when it stops sending data when we request
it.</p>
<pre class="literal-block">
struct peer_snubbed_alert: peer_alert
{
        // ...
};
</pre>
</div>
<div class="section" id="peer-unsnubbed-alert">
<h2>peer_unsnubbed_alert</h2>
<p>This alert is generated when a peer is unsnubbed. Essentially when it was snubbed for stalling
sending data, and now it started sending data again.</p>
<pre class="literal-block">
struct peer_unsnubbed_alert: peer_alert
{
        // ...
};
</pre>
</div>
<div class="section" id="peer-error-alert">
<h2>peer_error_alert</h2>
<p>This alert is generated when a peer sends invalid data over the peer-peer protocol. The peer
will be disconnected, but you get its ip address from the alert, to identify it.</p>
<p>The <tt class="docutils literal">error_code</tt> tells you what error caused this alert.</p>
<pre class="literal-block">
struct peer_error_alert: peer_alert
{
        // ...
        error_code error;
};
</pre>
</div>
<div class="section" id="peer-connected-alert">
<h2>peer_connected_alert</h2>
<p>This alert is generated when a peer is connected.</p>
<pre class="literal-block">
struct peer_connected_alert: peer_alert
{
        // ...
};
</pre>
</div>
<div class="section" id="peer-disconnected-alert">
<h2>peer_disconnected_alert</h2>
<p>This alert is generated when a peer is disconnected for any reason (other than the ones
covered by <tt class="docutils literal">peer_error_alert</tt>).</p>
<p>The <tt class="docutils literal">error_code</tt> tells you what error caused peer to disconnect.</p>
<pre class="literal-block">
struct peer_disconnected_alert: peer_alert
{
        // ...
        error_code error;
};
</pre>
</div>
<div class="section" id="invalid-request-alert">
<h2>invalid_request_alert</h2>
<p>This is a debug alert that is generated by an incoming invalid piece request.
<tt class="docutils literal">ip</tt> is the address of the peer and the <tt class="docutils literal">request</tt> is the actual incoming
request from the peer.</p>
<pre class="literal-block">
struct invalid_request_alert: peer_alert
{
        // ...
        peer_request request;
};


struct peer_request
{
        int piece;
        int start;
        int length;
        bool operator==(peer_request const&amp; r) const;
};
</pre>
<p>The <tt class="docutils literal">peer_request</tt> contains the values the client sent in its <tt class="docutils literal">request</tt> message. <tt class="docutils literal">piece</tt> is
the index of the piece it want data from, <tt class="docutils literal">start</tt> is the offset within the piece where the data
should be read, and <tt class="docutils literal">length</tt> is the amount of data it wants.</p>
</div>
<div class="section" id="request-dropped-alert">
<h2>request_dropped_alert</h2>
<p>This alert is generated when a peer rejects or ignores a piece request.</p>
<pre class="literal-block">
struct request_dropped_alert: peer_alert
{
        // ...
        int block_index;
        int piece_index;
};
</pre>
</div>
<div class="section" id="block-timeout-alert">
<h2>block_timeout_alert</h2>
<p>This alert is generated when a block request times out.</p>
<pre class="literal-block">
struct block_timeout_alert: peer_alert
{
        // ...
        int block_index;
        int piece_index;
};
</pre>
</div>
<div class="section" id="block-finished-alert">
<h2>block_finished_alert</h2>
<p>This alert is generated when a block request receives a response.</p>
<pre class="literal-block">
struct block_finished_alert: peer_alert
{
        // ...
        int block_index;
        int piece_index;
};
</pre>
</div>
<div class="section" id="lsd-peer-alert">
<h2>lsd_peer_alert</h2>
<p>This alert is generated when we receive a local service discovery message from a peer
for a torrent we're currently participating in.</p>
<pre class="literal-block">
struct lsd_peer_alert: peer_alert
{
        // ...
};
</pre>
</div>
<div class="section" id="file-completed-alert">
<h2>file_completed_alert</h2>
<p>This is posted whenever an individual file completes its download. i.e.
All pieces overlapping this file have passed their hash check.</p>
<pre class="literal-block">
struct file_completed_alert: torrent_alert
{
        // ...
        int index;
};
</pre>
<p>The <tt class="docutils literal">index</tt> member refers to the index of the file that completed.</p>
</div>
<div class="section" id="block-downloading-alert">
<h2>block_downloading_alert</h2>
<p>This alert is generated when a block request is sent to a peer.</p>
<pre class="literal-block">
struct block_downloading_alert: peer_alert
{
        // ...
        int block_index;
        int piece_index;
};
</pre>
</div>
<div class="section" id="unwanted-block-alert">
<h2>unwanted_block_alert</h2>
<p>This alert is generated when a block is received that was not requested or
whose request timed out.</p>
<pre class="literal-block">
struct unwanted_block_alert: peer_alert
{
        // ...
        int block_index;
        int piece_index;
};
</pre>
</div>
<div class="section" id="torrent-delete-failed-alert">
<h2>torrent_delete_failed_alert</h2>
<p>This alert is generated when a request to delete the files of a torrent fails.</p>
<p>The <tt class="docutils literal">error_code</tt> tells you why it failed.</p>
<pre class="literal-block">
struct torrent_delete_failed_alert: torrent_alert
{
        // ...
        error_code error;
};
</pre>
</div>
<div class="section" id="torrent-deleted-alert">
<h2>torrent_deleted_alert</h2>
<p>This alert is generated when a request to delete the files of a torrent complete.</p>
<p>The <tt class="docutils literal">info_hash</tt> is the info-hash of the torrent that was just deleted. Most of
the time the torrent_handle in the <tt class="docutils literal">torrent_alert</tt> will be invalid by the time
this alert arrives, since the torrent is being deleted. The <tt class="docutils literal">info_hash</tt> member
is hence the main way of identifying which torrent just completed the delete.</p>
<p>This alert is posted in the <tt class="docutils literal">storage_notification</tt> category, and that bit
needs to be set in the alert mask.</p>
<pre class="literal-block">
struct torrent_deleted_alert: torrent_alert
{
        // ...
        sha1_hash info_hash;
};
</pre>
</div>
<div class="section" id="torrent-finished-alert">
<h2>torrent_finished_alert</h2>
<p>This alert is generated when a torrent switches from being a downloader to a seed.
It will only be generated once per torrent. It contains a torrent_handle to the
torrent in question.</p>
<p>There are no additional data members in this alert.</p>
</div>
<div class="section" id="performance-alert">
<h2>performance_alert</h2>
<p>This alert is generated when a limit is reached that might have a negative impact on
upload or download rate performance.</p>
<pre class="literal-block">
struct performance_alert: torrent_alert
{
        // ...

        enum performance_warning_t
        {
                outstanding_disk_buffer_limit_reached,
                outstanding_request_limit_reached,
                upload_limit_too_low,
                download_limit_too_low,
                send_buffer_watermark_too_low,
                too_many_optimistic_unchoke_slots,
                too_high_disk_queue_limit,
                too_few_outgoing_ports
        };

        performance_warning_t warning_code;
};
</pre>
<dl class="docutils">
<dt>outstanding_disk_buffer_limit_reached</dt>
<dd>This warning means that the number of bytes queued to be written to disk
exceeds the max disk byte queue setting (<tt class="docutils literal"><span class="pre">session_settings::max_queued_disk_bytes</span></tt>).
This might restrict the download rate, by not queuing up enough write jobs
to the disk I/O thread. When this alert is posted, peer connections are
temporarily stopped from downloading, until the queued disk bytes have fallen
below the limit again. Unless your <tt class="docutils literal">max_queued_disk_bytes</tt> setting is already
high, you might want to increase it to get better performance.</dd>
<dt>outstanding_request_limit_reached</dt>
<dd>This is posted when libtorrent would like to send more requests to a peer,
but it's limited by <tt class="docutils literal"><span class="pre">session_settings::max_out_request_queue</span></tt>. The queue length
libtorrent is trying to achieve is determined by the download rate and the
assumed round-trip-time (<tt class="docutils literal"><span class="pre">session_settings::request_queue_time</span></tt>). The assumed
rount-trip-time is not limited to just the network RTT, but also the remote disk
access time and message handling time. It defaults to 3 seconds. The target number
of outstanding requests is set to fill the bandwidth-delay product (assumed RTT
times download rate divided by number of bytes per request). When this alert
is posted, there is a risk that the number of outstanding requests is too low
and limits the download rate. You might want to increase the <tt class="docutils literal">max_out_request_queue</tt>
setting.</dd>
<dt>upload_limit_too_low</dt>
<dd>This warning is posted when the amount of TCP/IP overhead is greater than the
upload rate limit. When this happens, the TCP/IP overhead is caused by a much
faster download rate, triggering TCP ACK packets. These packets eat into the
rate limit specified to libtorrent. When the overhead traffic is greater than
the rate limit, libtorrent will not be able to send any actual payload, such
as piece requests. This means the download rate will suffer, and new requests
can be sent again. There will be an equilibrium where the download rate, on
average, is about 20 times the upload rate limit. If you want to maximize the
download rate, increase the upload rate limit above 5% of your download capacity.</dd>
<dt>download_limit_too_low</dt>
<dd>This is the same warning as <tt class="docutils literal">upload_limit_too_low</tt> but referring to the download
limit instead of upload. This suggests that your download rate limit is mcuh lower
than your upload capacity. Your upload rate will suffer. To maximize upload rate,
make sure your download rate limit is above 5% of your upload capacity.</dd>
<dt>send_buffer_watermark_too_low</dt>
<dd><p class="first">We're stalled on the disk. We want to write to the socket, and we can write
but our send buffer is empty, waiting to be refilled from the disk.
This either means the disk is slower than the network connection
or that our send buffer watermark is too small, because we can
send it all before the disk gets back to us.
The number of bytes that we keep outstanding, requested from the disk, is calculated
as follows:</p>
<pre class="literal-block">
min(512, max(upload_rate * send_buffer_watermark_factor / 100, send_buffer_watermark))
</pre>
<p class="last">If you receive this alert, you migth want to either increase your <tt class="docutils literal">send_buffer_watermark</tt>
or <tt class="docutils literal">send_buffer_watermark_factor</tt>.</p>
</dd>
<dt>too_many_optimistic_unchoke_slots</dt>
<dd>If the half (or more) of all upload slots are set as optimistic unchoke slots, this
warning is issued. You probably want more regular (rate based) unchoke slots.</dd>
<dt>too_high_disk_queue_limit</dt>
<dd>If the disk write queue ever grows larger than half of the cache size, this warning
is posted. The disk write queue eats into the total disk cache and leaves very little
left for the actual cache. This causes the disk cache to oscillate in evicting large
portions of the cache before allowing peers to download any more, onto the disk write
queue. Either lower <tt class="docutils literal">max_queued_disk_bytes</tt> or increase <tt class="docutils literal">cache_size</tt>.</dd>
<dt>too_few_outgoing_ports</dt>
<dd>This is generated if outgoing peer connections are failing because of <em>address in use</em>
errors, indicating that <tt class="docutils literal"><span class="pre">session_settings::outgoing_ports</span></tt> is set and is too small of
a range. Consider not using the <tt class="docutils literal">outgoing_ports</tt> setting at all, or widen the range to
include more ports.</dd>
</dl>
</div>
<div class="section" id="state-changed-alert">
<h2>state_changed_alert</h2>
<p>Generated whenever a torrent changes its state.</p>
<pre class="literal-block">
struct state_changed_alert: torrent_alert
{
        // ...

        torrent_status::state_t state;
        torrent_status::state_t prev_state;
};
</pre>
<p><tt class="docutils literal">state</tt> is the new state of the torrent. <tt class="docutils literal">prev_state</tt> is the previous state.</p>
</div>
<div class="section" id="metadata-failed-alert">
<h2>metadata_failed_alert</h2>
<p>This alert is generated when the metadata has been completely received and the info-hash
failed to match it. i.e. the metadata that was received was corrupt. libtorrent will
automatically retry to fetch it in this case. This is only relevant when running a
torrent-less download, with the metadata extension provided by libtorrent.</p>
<p>There are no additional data members in this alert.</p>
</div>
<div class="section" id="metadata-received-alert">
<h2>metadata_received_alert</h2>
<p>This alert is generated when the metadata has been completely received and the torrent
can start downloading. It is not generated on torrents that are started with metadata, but
only those that needs to download it from peers (when utilizing the libtorrent extension).</p>
<p>There are no additional data members in this alert.</p>
<p>Typically, when receiving this alert, you would want to save the torrent file in order
to load it back up again when the session is restarted. Here's an example snippet of
code to do that:</p>
<pre class="literal-block">
torrent_handle h = alert-&gt;handle();
if (h.is_valid()) {
        boost::intrusive_ptr&lt;torrent_info const&gt; ti = h.torrent_file();
        create_torrent ct(*ti);
        entry te = ct.generate();
        std::vector&lt;char&gt; buffer;
        bencode(std::back_inserter(buffer), te);
        FILE* f = fopen((to_hex(ti-&gt;info_hash().to_string()) + &quot;.torrent&quot;).c_str(), &quot;w+&quot;);
        if (f) {
                fwrite(&amp;buffer[0], 1, buffer.size(), f);
                fclose(f);
        }
}
</pre>
</div>
<div class="section" id="fastresume-rejected-alert">
<h2>fastresume_rejected_alert</h2>
<p>This alert is generated when a fastresume file has been passed to <tt class="docutils literal">add_torrent</tt> but the
files on disk did not match the fastresume file. The <tt class="docutils literal">error_code</tt> explains the reason why the
resume file was rejected.</p>
<pre class="literal-block">
struct fastresume_rejected_alert: torrent_alert
{
        // ...
        error_code error;
};
</pre>
</div>
<div class="section" id="peer-blocked-alert">
<h2>peer_blocked_alert</h2>
<p>This alert is generated when a peer is blocked by the IP filter. The <tt class="docutils literal">ip</tt> member is the
address that was blocked.</p>
<pre class="literal-block">
struct peer_blocked_alert: torrent_alert
{
        // ...
        address ip;
};
</pre>
</div>
<div class="section" id="storage-moved-alert">
<h2>storage_moved_alert</h2>
<p>The <tt class="docutils literal">storage_moved_alert</tt> is generated when all the disk IO has completed and the
files have been moved, as an effect of a call to <tt class="docutils literal"><span class="pre">torrent_handle::move_storage</span></tt>. This
is useful to synchronize with the actual disk. The <tt class="docutils literal">path</tt> member is the new path of
the storage.</p>
<pre class="literal-block">
struct storage_moved_alert: torrent_alert
{
        // ...
        std::string path;
};
</pre>
</div>
<div class="section" id="storage-moved-failed-alert">
<h2>storage_moved_failed_alert</h2>
<p>The <tt class="docutils literal">storage_moved_failed_alert</tt> is generated when an attempt to move the storage
(via torrent_handle::move_storage()) fails.</p>
<pre class="literal-block">
struct storage_moved_failed_alert: torrent_alert
{
        // ...
        error_code error;
};
</pre>
</div>
<div class="section" id="torrent-paused-alert">
<h2>torrent_paused_alert</h2>
<p>This alert is generated as a response to a <tt class="docutils literal"><span class="pre">torrent_handle::pause</span></tt> request. It is
generated once all disk IO is complete and the files in the torrent have been closed.
This is useful for synchronizing with the disk.</p>
<p>There are no additional data members in this alert.</p>
</div>
<div class="section" id="torrent-resumed-alert">
<h2>torrent_resumed_alert</h2>
<p>This alert is generated as a response to a <tt class="docutils literal"><span class="pre">torrent_handle::resume</span></tt> request. It is
generated when a torrent goes from a paused state to an active state.</p>
<p>There are no additional data members in this alert.</p>
</div>
<div class="section" id="save-resume-data-alert">
<h2>save_resume_data_alert</h2>
<p>This alert is generated as a response to a <tt class="docutils literal"><span class="pre">torrent_handle::save_resume_data</span></tt> request.
It is generated once the disk IO thread is done writing the state for this torrent.
The <tt class="docutils literal">resume_data</tt> member points to the resume data.</p>
<pre class="literal-block">
struct save_resume_data_alert: torrent_alert
{
        // ...
        boost::shared_ptr&lt;entry&gt; resume_data;
};
</pre>
</div>
<div class="section" id="save-resume-data-failed-alert">
<h2>save_resume_data_failed_alert</h2>
<p>This alert is generated instead of <tt class="docutils literal">save_resume_data_alert</tt> if there was an error
generating the resume data. <tt class="docutils literal">error</tt> describes what went wrong.</p>
<pre class="literal-block">
struct save_resume_data_failed_alert: torrent_alert
{
        // ...
        error_code error;
};
</pre>
</div>
<div class="section" id="stats-alert">
<h2>stats_alert</h2>
<p>This alert is posted approximately once every second, and it contains
byte counters of most statistics that's tracked for torrents. Each active
torrent posts these alerts regularly.</p>
<pre class="literal-block">
struct stats_alert: torrent_alert
{
        // ...
        enum stats_channel
        {
                upload_payload,
                upload_protocol,
                upload_ip_protocol,
                upload_dht_protocol,
                upload_tracker_protocol,
                download_payload,
                download_protocol,
                download_ip_protocol,
                download_dht_protocol,
                download_tracker_protocol,
                num_channels
        };

        int transferred[num_channels];
        int interval;
};
</pre>
<p><tt class="docutils literal">transferred</tt> this is an array of samples. The enum describes what each
sample is a measurement of. All of these are raw, and not smoothing is performed.</p>
<p><tt class="docutils literal">interval</tt> the number of milliseconds during which these stats
were collected. This is typically just above 1000, but if CPU is
limited, it may be higher than that.</p>
</div>
<div class="section" id="cache-flushed-alert">
<h2>cache_flushed_alert</h2>
<p>This alert is posted when the disk cache has been flushed for a specific torrent
as a result of a call to <a class="reference internal" href="#flush-cache">flush_cache()</a>. This alert belongs to the
<tt class="docutils literal">storage_notification</tt> category, which must be enabled to let this alert through.
The alert is also posted when removing a torrent from the session, once the outstanding
cache flush is complete and the torrent does no longer have any files open.</p>
<pre class="literal-block">
struct flush_cached_alert: torrent_alert
{
        // ...
};
</pre>
</div>
<div class="section" id="torrent-need-cert-alert">
<h2>torrent_need_cert_alert</h2>
<p>This is always posted for SSL torrents. This is a reminder to the client that
the torrent won't work unless torrent_handle::set_ssl_certificate() is called with
a valid certificate. Valid certificates MUST be signed by the SSL certificate
in the .torrent file.</p>
<pre class="literal-block">
struct torrent_need_cert_alert: tracker_alert
{
        // ...
};
</pre>
</div>
<div class="section" id="dht-announce-alert">
<h2>dht_announce_alert</h2>
<p>This alert is generated when a DHT node announces to an info-hash on our DHT node. It belongs
to the <tt class="docutils literal">dht_notification</tt> category.</p>
<pre class="literal-block">
struct dht_announce_alert: alert
{
        // ...
        address ip;
        int port;
        sha1_hash info_hash;
};
</pre>
</div>
<div class="section" id="dht-get-peers-alert">
<h2>dht_get_peers_alert</h2>
<p>This alert is generated when a DHT node sends a <tt class="docutils literal">get_peers</tt> message to our DHT node.
It belongs to the <tt class="docutils literal">dht_notification</tt> category.</p>
<pre class="literal-block">
struct dht_get_peers_alert: alert
{
        // ...
        sha1_hash info_hash;
};
</pre>
</div>
<div class="section" id="dht-reply-alert">
<h2>dht_reply_alert</h2>
<p>This alert is generated each time the DHT receives peers from a node. <tt class="docutils literal">num_peers</tt>
is the number of peers we received in this packet. Typically these packets are
received from multiple DHT nodes, and so the alerts are typically generated
a few at a time.</p>
<pre class="literal-block">
struct dht_reply_alert: tracker_alert
{
        // ...
        int num_peers;
};
</pre>
</div>
<div class="section" id="dht-bootstrap-alert">
<h2>dht_bootstrap_alert</h2>
<p>This alert is posted when the initial DHT bootstrap is done. There's no any other
relevant information associated with this alert.</p>
<pre class="literal-block">
struct dht_bootstrap_alert: alert
{
        // ...
};
</pre>
</div>
<div class="section" id="anonymous-mode-alert">
<h2>anonymous_mode_alert</h2>
<p>This alert is posted when a bittorrent feature is blocked because of the
anonymous mode. For instance, if the tracker proxy is not set up, no
trackers will be used, because trackers can only be used through proxies
when in anonymous mode.</p>
<pre class="literal-block">
struct anonymous_mode_alert: tracker_alert
{
        // ...
        enum kind_t
        {
                tracker_not_anonymous = 1
        };
        int kind;
        std::string str;
};
</pre>
<p><tt class="docutils literal">kind</tt> specifies what error this is, it's one of:</p>
<p><tt class="docutils literal">tracker_not_anonymous</tt> means that there's no proxy set up for tracker
communication and the tracker will not be contacted. The tracker which
this failed for is specified in the <tt class="docutils literal">str</tt> member.</p>
</div>
<div class="section" id="rss-alert">
<h2>rss_alert</h2>
<p>This alert is posted on RSS feed events such as start of RSS feed updates,
successful completed updates and errors during updates.</p>
<p>This alert is only posted if the <tt class="docutils literal">rss_notifications</tt> category is enabled
in the alert mask.</p>
<pre class="literal-block">
struct rss_alert: alert
{
        // ..
        virtual std::string message() const;

        enum state_t
        {
                state_updating, state_updated, state_error
        };

        feed_handle handle;
        std::string url;
        int state;
        error_code error;
};
</pre>
<p><tt class="docutils literal">handle</tt> is the handle to the feed which generated this alert.</p>
<p><tt class="docutils literal">url</tt> is a short cut to access the url of the feed, without
having to call <tt class="docutils literal">get_settings()</tt>.</p>
<p><tt class="docutils literal">state</tt> is one of:</p>
<dl class="docutils">
<dt><tt class="docutils literal"><span class="pre">rss_alert::state_updating</span></tt></dt>
<dd>An update of this feed was just initiated, it will either succeed
or fail soon.</dd>
<dt><tt class="docutils literal"><span class="pre">rss_alert::state_updated</span></tt></dt>
<dd>The feed just completed a successful update, there may be new items
in it. If you're adding torrents manually, you may want to request
the feed status of the feed and look through the <tt class="docutils literal">items</tt> vector.</dd>
<dt><tt class="docutils literal"><span class="pre">rss_akert::state_error</span></tt></dt>
<dd>An error just occurred. See the <tt class="docutils literal">error</tt> field for information on
what went wrong.</dd>
</dl>
<p><tt class="docutils literal">error</tt> is an error code used for when an error occurs on the feed.</p>
</div>
<div class="section" id="incoming-connection-alert">
<h2>incoming_connection_alert</h2>
<p>The incoming connection alert is posted every time we successfully accept
an incoming connection, through any mean. The most straigh-forward ways
of accepting incoming connections are through the TCP listen socket and
the UDP listen socket for uTP sockets. However, connections may also be
accepted ofer a Socks5 or i2p listen socket, or via a torrent specific
listen socket for SSL torrents.</p>
<pre class="literal-block">
struct incoming_connection_alert: alert
{
        // ...
        virtual std::string message() const;

        int socket_type;
        tcp::endpoint ip;
};
</pre>
<p><tt class="docutils literal">socket_type</tt> tells you what kind of socket the connection was accepted
as:</p>
<table border="1" class="docutils">
<colgroup>
<col width="21%" />
<col width="79%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">value</th>
<th class="head">type</th>
</tr>
</thead>
<tbody valign="top">
<tr><td>0</td>
<td>none (no socket instantiated)</td>
</tr>
<tr><td>1</td>
<td>TCP</td>
</tr>
<tr><td>2</td>
<td>Socks5</td>
</tr>
<tr><td>3</td>
<td>HTTP</td>
</tr>
<tr><td>4</td>
<td>uTP</td>
</tr>
<tr><td>5</td>
<td>i2p</td>
</tr>
<tr><td>6</td>
<td>SSL/TCP</td>
</tr>
<tr><td>7</td>
<td>SSL/Socks5</td>
</tr>
<tr><td>8</td>
<td>HTTPS (SSL/HTTP)</td>
</tr>
<tr><td>9</td>
<td>SSL/uTP</td>
</tr>
</tbody>
</table>
<p><tt class="docutils literal">ip</tt> is the IP address and port the connection came from.</p>
</div>
<div class="section" id="state-update-alert">
<h2>state_update_alert</h2>
<p>This alert is only posted when requested by the user, by calling <a class="reference internal" href="#post-torrent-updates">post_torrent_updates()</a>
on the session. It contains the torrent status of all torrents that changed
since last time this message was posted. Its category is <tt class="docutils literal">status_notification</tt>, but
it's not subject to filtering, since it's only manually posted anyway.</p>
<pre class="literal-block">
struct state_update_alert: alert
{
        // ...
        std::vector&lt;torrent_status&gt; status;
};
</pre>
<p><tt class="docutils literal">status</tt> contains the torrent status of all torrents that changed since last time
this message was posted. Note that you can map a torrent status to a specific torrent
via its <tt class="docutils literal">handle</tt> member. The receiving end is suggested to have all torrents sorted
by the <tt class="docutils literal">torrent_handle</tt> or hashed by it, for efficient updates.</p>
</div>
</div>
<div class="section" id="alert-dispatcher">
<h1>alert dispatcher</h1>
<p>The <tt class="docutils literal">handle_alert</tt> class is defined in <tt class="docutils literal">&lt;libtorrent/alert.hpp&gt;</tt>.</p>
<p>Examples usage:</p>
<pre class="literal-block">
struct my_handler
{
        void operator()(portmap_error_alert const&amp; a) const
        {
                std::cout &lt;&lt; &quot;Portmapper: &quot; &lt;&lt; a.msg &lt;&lt; std::endl;
        }

        void operator()(tracker_warning_alert const&amp; a) const
        {
                std::cout &lt;&lt; &quot;Tracker warning: &quot; &lt;&lt; a.msg &lt;&lt; std::endl;
        }

        void operator()(torrent_finished_alert const&amp; a) const
        {
                // write fast resume data
                // ...

                std::cout &lt;&lt; a.handle.torrent_file()-&gt;name() &lt;&lt; &quot;completed&quot;
                        &lt;&lt; std::endl;
        }
};
</pre>
<pre class="literal-block">
std::auto_ptr&lt;alert&gt; a;
a = ses.pop_alert();
my_handler h;
while (a.get())
{
        handle_alert&lt;portmap_error_alert
                , tracker_warning_alert
                , torrent_finished_alert
        &gt;::handle_alert(h, a);
        a = ses.pop_alert();
}
</pre>
<p>In this example 3 alert types are used. You can use any number of template
parameters to select between more types. If the number of types are more than
15, you can define <tt class="docutils literal">TORRENT_MAX_ALERT_TYPES</tt> to a greater number before
including <tt class="docutils literal">&lt;libtorrent/alert.hpp&gt;</tt>.</p>
</div>
<div class="section" id="exceptions">
<h1>exceptions</h1>
<p>Many functions in libtorrent have two versions, one that throws exceptions on
errors and one that takes an <tt class="docutils literal">error_code</tt> reference which is filled with the
error code on errors.</p>
<p>There is one exception class that is used for errors in libtorrent, it is based
on boost.system's <tt class="docutils literal">error_code</tt> class to carry the error code.</p>
<div class="section" id="libtorrent-exception">
<h2>libtorrent_exception</h2>
<pre class="literal-block">
struct libtorrent_exception: std::exception
{
        libtorrent_exception(error_code const&amp; s);
        virtual const char* what() const throw();
        virtual ~libtorrent_exception() throw() {}
        boost::system::error_code error() const;
};
</pre>
</div>
</div>
<div class="section" id="error-code">
<h1>error_code</h1>
<p>libtorrent uses boost.system's <tt class="docutils literal">error_code</tt> class to represent errors. libtorrent has
its own error category (<tt class="docutils literal"><span class="pre">libtorrent::get_libtorrent_category()</span></tt>) whith the following error
codes:</p>
<table border="1" class="docutils">
<colgroup>
<col width="5%" />
<col width="37%" />
<col width="58%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">code</th>
<th class="head">symbol</th>
<th class="head">description</th>
</tr>
</thead>
<tbody valign="top">
<tr><td>0</td>
<td>no_error</td>
<td>Not an error</td>
</tr>
<tr><td>1</td>
<td>file_collision</td>
<td>Two torrents has files which end up overwriting each other</td>
</tr>
<tr><td>2</td>
<td>failed_hash_check</td>
<td>A piece did not match its piece hash</td>
</tr>
<tr><td>3</td>
<td>torrent_is_no_dict</td>
<td>The .torrent file does not contain a bencoded dictionary at
its top level</td>
</tr>
<tr><td>4</td>
<td>torrent_missing_info</td>
<td>The .torrent file does not have an <tt class="docutils literal">info</tt> dictionary</td>
</tr>
<tr><td>5</td>
<td>torrent_info_no_dict</td>
<td>The .torrent file's <tt class="docutils literal">info</tt> entry is not a dictionary</td>
</tr>
<tr><td>6</td>
<td>torrent_missing_piece_length</td>
<td>The .torrent file does not have a <tt class="docutils literal">piece length</tt> entry</td>
</tr>
<tr><td>7</td>
<td>torrent_missing_name</td>
<td>The .torrent file does not have a <tt class="docutils literal">name</tt> entry</td>
</tr>
<tr><td>8</td>
<td>torrent_invalid_name</td>
<td>The .torrent file's name entry is invalid</td>
</tr>
<tr><td>9</td>
<td>torrent_invalid_length</td>
<td>The length of a file, or of the whole .torrent file is invalid.
Either negative or not an integer</td>
</tr>
<tr><td>10</td>
<td>torrent_file_parse_failed</td>
<td>Failed to parse a file entry in the .torrent</td>
</tr>
<tr><td>11</td>
<td>torrent_missing_pieces</td>
<td>The <tt class="docutils literal">pieces</tt> field is missing or invalid in the .torrent file</td>
</tr>
<tr><td>12</td>
<td>torrent_invalid_hashes</td>
<td>The <tt class="docutils literal">pieces</tt> string has incorrect length</td>
</tr>
<tr><td>13</td>
<td>too_many_pieces_in_torrent</td>
<td>The .torrent file has more pieces than is supported by libtorrent</td>
</tr>
<tr><td>14</td>
<td>invalid_swarm_metadata</td>
<td>The metadata (.torrent file) that was received from the swarm
matched the info-hash, but failed to be parsed</td>
</tr>
<tr><td>15</td>
<td>invalid_bencoding</td>
<td>The file or buffer is not correctly bencoded</td>
</tr>
<tr><td>16</td>
<td>no_files_in_torrent</td>
<td>The .torrent file does not contain any files</td>
</tr>
<tr><td>17</td>
<td>invalid_escaped_string</td>
<td>The string was not properly url-encoded as expected</td>
</tr>
<tr><td>18</td>
<td>session_is_closing</td>
<td>Operation is not permitted since the session is shutting down</td>
</tr>
<tr><td>19</td>
<td>duplicate_torrent</td>
<td>There's already a torrent with that info-hash added to the
session</td>
</tr>
<tr><td>20</td>
<td>invalid_torrent_handle</td>
<td>The supplied torrent_handle is not referring to a valid torrent</td>
</tr>
<tr><td>21</td>
<td>invalid_entry_type</td>
<td>The type requested from the entry did not match its type</td>
</tr>
<tr><td>22</td>
<td>missing_info_hash_in_uri</td>
<td>The specified URI does not contain a valid info-hash</td>
</tr>
<tr><td>23</td>
<td>file_too_short</td>
<td>One of the files in the torrent was unexpectadly small. This
might be caused by files being changed by an external process</td>
</tr>
<tr><td>24</td>
<td>unsupported_url_protocol</td>
<td>The URL used an unknown protocol. Currently <tt class="docutils literal">http</tt> and
<tt class="docutils literal">https</tt> (if built with openssl support) are recognized. For
trackers <tt class="docutils literal">udp</tt> is recognized as well.</td>
</tr>
<tr><td>25</td>
<td>url_parse_error</td>
<td>The URL did not conform to URL syntax and failed to be parsed</td>
</tr>
<tr><td>26</td>
<td>peer_sent_empty_piece</td>
<td>The peer sent a 'piece' message of length 0</td>
</tr>
<tr><td>27</td>
<td>parse_failed</td>
<td>A bencoded structure was currupt and failed to be parsed</td>
</tr>
<tr><td>28</td>
<td>invalid_file_tag</td>
<td>The fast resume file was missing or had an invalid file version
tag</td>
</tr>
<tr><td>29</td>
<td>missing_info_hash</td>
<td>The fast resume file was missing or had an invalid info-hash</td>
</tr>
<tr><td>30</td>
<td>mismatching_info_hash</td>
<td>The info-hash in the resume file did not match the torrent</td>
</tr>
<tr><td>31</td>
<td>invalid_hostname</td>
<td>The URL contained an invalid hostname</td>
</tr>
<tr><td>32</td>
<td>invalid_port</td>
<td>The URL had an invalid port</td>
</tr>
<tr><td>33</td>
<td>port_blocked</td>
<td>The port is blocked by the port-filter, and prevented the
connection</td>
</tr>
<tr><td>34</td>
<td>expected_close_bracket_in_address</td>
<td>The IPv6 address was expected to end with ']'</td>
</tr>
<tr><td>35</td>
<td>destructing_torrent</td>
<td>The torrent is being destructed, preventing the operation to
succeed</td>
</tr>
<tr><td>36</td>
<td>timed_out</td>
<td>The connection timed out</td>
</tr>
<tr><td>37</td>
<td>upload_upload_connection</td>
<td>The peer is upload only, and we are upload only. There's no point
in keeping the connection</td>
</tr>
<tr><td>38</td>
<td>uninteresting_upload_peer</td>
<td>The peer is upload only, and we're not interested in it. There's
no point in keeping the connection</td>
</tr>
<tr><td>39</td>
<td>invalid_info_hash</td>
<td>The peer sent an unknown info-hash</td>
</tr>
<tr><td>40</td>
<td>torrent_paused</td>
<td>The torrent is paused, preventing the operation from succeeding</td>
</tr>
<tr><td>41</td>
<td>invalid_have</td>
<td>The peer sent an invalid have message, either wrong size or
referring to a piece that doesn't exist in the torrent</td>
</tr>
<tr><td>42</td>
<td>invalid_bitfield_size</td>
<td>The bitfield message had the incorrect size</td>
</tr>
<tr><td>43</td>
<td>too_many_requests_when_choked</td>
<td>The peer kept requesting pieces after it was choked, possible
abuse attempt.</td>
</tr>
<tr><td>44</td>
<td>invalid_piece</td>
<td>The peer sent a piece message that does not correspond to a
piece request sent by the client</td>
</tr>
<tr><td>45</td>
<td>no_memory</td>
<td>memory allocation failed</td>
</tr>
<tr><td>46</td>
<td>torrent_aborted</td>
<td>The torrent is aborted, preventing the operation to succeed</td>
</tr>
<tr><td>47</td>
<td>self_connection</td>
<td>The peer is a connection to ourself, no point in keeping it</td>
</tr>
<tr><td>48</td>
<td>invalid_piece_size</td>
<td>The peer sent a piece message with invalid size, either negative
or greater than one block</td>
</tr>
<tr><td>49</td>
<td>timed_out_no_interest</td>
<td>The peer has not been interesting or interested in us for too
long, no point in keeping it around</td>
</tr>
<tr><td>50</td>
<td>timed_out_inactivity</td>
<td>The peer has not said anything in a long time, possibly dead</td>
</tr>
<tr><td>51</td>
<td>timed_out_no_handshake</td>
<td>The peer did not send a handshake within a reasonable amount of
time, it might not be a bittorrent peer</td>
</tr>
<tr><td>52</td>
<td>timed_out_no_request</td>
<td>The peer has been unchoked for too long without requesting any
data. It might be lying about its interest in us</td>
</tr>
<tr><td>53</td>
<td>invalid_choke</td>
<td>The peer sent an invalid choke message</td>
</tr>
<tr><td>54</td>
<td>invalid_unchoke</td>
<td>The peer send an invalid unchoke message</td>
</tr>
<tr><td>55</td>
<td>invalid_interested</td>
<td>The peer sent an invalid interested message</td>
</tr>
<tr><td>56</td>
<td>invalid_not_interested</td>
<td>The peer sent an invalid not-interested message</td>
</tr>
<tr><td>57</td>
<td>invalid_request</td>
<td>The peer sent an invalid piece request message</td>
</tr>
<tr><td>58</td>
<td>invalid_hash_list</td>
<td>The peer sent an invalid hash-list message (this is part of the
merkle-torrent extension)</td>
</tr>
<tr><td>59</td>
<td>invalid_hash_piece</td>
<td>The peer sent an invalid hash-piece message (this is part of the
merkle-torrent extension)</td>
</tr>
<tr><td>60</td>
<td>invalid_cancel</td>
<td>The peer sent an invalid cancel message</td>
</tr>
<tr><td>61</td>
<td>invalid_dht_port</td>
<td>The peer sent an invalid DHT port-message</td>
</tr>
<tr><td>62</td>
<td>invalid_suggest</td>
<td>The peer sent an invalid suggest piece-message</td>
</tr>
<tr><td>63</td>
<td>invalid_have_all</td>
<td>The peer sent an invalid have all-message</td>
</tr>
<tr><td>64</td>
<td>invalid_have_none</td>
<td>The peer sent an invalid have none-message</td>
</tr>
<tr><td>65</td>
<td>invalid_reject</td>
<td>The peer sent an invalid reject message</td>
</tr>
<tr><td>66</td>
<td>invalid_allow_fast</td>
<td>The peer sent an invalid allow fast-message</td>
</tr>
<tr><td>67</td>
<td>invalid_extended</td>
<td>The peer sent an invalid extesion message ID</td>
</tr>
<tr><td>68</td>
<td>invalid_message</td>
<td>The peer sent an invalid message ID</td>
</tr>
<tr><td>69</td>
<td>sync_hash_not_found</td>
<td>The synchronization hash was not found in the encrypted handshake</td>
</tr>
<tr><td>70</td>
<td>invalid_encryption_constant</td>
<td>The encryption constant in the handshake is invalid</td>
</tr>
<tr><td>71</td>
<td>no_plaintext_mode</td>
<td>The peer does not support plaintext, which is the selected mode</td>
</tr>
<tr><td>72</td>
<td>no_rc4_mode</td>
<td>The peer does not support rc4, which is the selected mode</td>
</tr>
<tr><td>73</td>
<td>unsupported_encryption_mode</td>
<td>The peer does not support any of the encryption modes that the
client supports</td>
</tr>
<tr><td>74</td>
<td>unsupported_encryption_mode_selected</td>
<td>The peer selected an encryption mode that the client did not
advertise and does not support</td>
</tr>
<tr><td>75</td>
<td>invalid_pad_size</td>
<td>The pad size used in the encryption handshake is of invalid size</td>
</tr>
<tr><td>76</td>
<td>invalid_encrypt_handshake</td>
<td>The encryption handshake is invalid</td>
</tr>
<tr><td>77</td>
<td>no_incoming_encrypted</td>
<td>The client is set to not support incoming encrypted connections
and this is an encrypted connection</td>
</tr>
<tr><td>78</td>
<td>no_incoming_regular</td>
<td>The client is set to not support incoming regular bittorrent
connections, and this is a regular connection</td>
</tr>
<tr><td>79</td>
<td>duplicate_peer_id</td>
<td>The client is already connected to this peer-ID</td>
</tr>
<tr><td>80</td>
<td>torrent_removed</td>
<td>Torrent was removed</td>
</tr>
<tr><td>81</td>
<td>packet_too_large</td>
<td>The packet size exceeded the upper sanity check-limit</td>
</tr>
<tr><td>82</td>
<td>reserved</td>
<td>&nbsp;</td>
</tr>
<tr><td>83</td>
<td>http_error</td>
<td>The web server responded with an error</td>
</tr>
<tr><td>84</td>
<td>missing_location</td>
<td>The web server response is missing a location header</td>
</tr>
<tr><td>85</td>
<td>invalid_redirection</td>
<td>The web seed redirected to a path that no longer matches the
.torrent directory structure</td>
</tr>
<tr><td>86</td>
<td>redirecting</td>
<td>The connection was closed becaused it redirected to a different
URL</td>
</tr>
<tr><td>87</td>
<td>invalid_range</td>
<td>The HTTP range header is invalid</td>
</tr>
<tr><td>88</td>
<td>no_content_length</td>
<td>The HTTP response did not have a content length</td>
</tr>
<tr><td>89</td>
<td>banned_by_ip_filter</td>
<td>The IP is blocked by the IP filter</td>
</tr>
<tr><td>90</td>
<td>too_many_connections</td>
<td>At the connection limit</td>
</tr>
<tr><td>91</td>
<td>peer_banned</td>
<td>The peer is marked as banned</td>
</tr>
<tr><td>92</td>
<td>stopping_torrent</td>
<td>The torrent is stopping, causing the operation to fail</td>
</tr>
<tr><td>93</td>
<td>too_many_corrupt_pieces</td>
<td>The peer has sent too many corrupt pieces and is banned</td>
</tr>
<tr><td>94</td>
<td>torrent_not_ready</td>
<td>The torrent is not ready to receive peers</td>
</tr>
<tr><td>95</td>
<td>peer_not_constructed</td>
<td>The peer is not completely constructed yet</td>
</tr>
<tr><td>96</td>
<td>session_closing</td>
<td>The session is closing, causing the operation to fail</td>
</tr>
<tr><td>97</td>
<td>optimistic_disconnect</td>
<td>The peer was disconnected in order to leave room for a
potentially better peer</td>
</tr>
<tr><td>98</td>
<td>torrent_finished</td>
<td>The torrent is finished</td>
</tr>
<tr><td>99</td>
<td>no_router</td>
<td>No UPnP router found</td>
</tr>
<tr><td>100</td>
<td>metadata_too_large</td>
<td>The metadata message says the metadata exceeds the limit</td>
</tr>
<tr><td>101</td>
<td>invalid_metadata_request</td>
<td>The peer sent an invalid metadata request message</td>
</tr>
<tr><td>102</td>
<td>invalid_metadata_size</td>
<td>The peer advertised an invalid metadata size</td>
</tr>
<tr><td>103</td>
<td>invalid_metadata_offset</td>
<td>The peer sent a message with an invalid metadata offset</td>
</tr>
<tr><td>104</td>
<td>invalid_metadata_message</td>
<td>The peer sent an invalid metadata message</td>
</tr>
<tr><td>105</td>
<td>pex_message_too_large</td>
<td>The peer sent a peer exchange message that was too large</td>
</tr>
<tr><td>106</td>
<td>invalid_pex_message</td>
<td>The peer sent an invalid peer exchange message</td>
</tr>
<tr><td>107</td>
<td>invalid_lt_tracker_message</td>
<td>The peer sent an invalid tracker exchange message</td>
</tr>
<tr><td>108</td>
<td>too_frequent_pex</td>
<td>The peer sent an pex messages too often. This is a possible
attempt of and attack</td>
</tr>
<tr><td>109</td>
<td>no_metadata</td>
<td>The operation failed because it requires the torrent to have
the metadata (.torrent file) and it doesn't have it yet.
This happens for magnet links before they have downloaded the
metadata, and also torrents added by URL.</td>
</tr>
<tr><td>110</td>
<td>invalid_dont_have</td>
<td>The peer sent an invalid <tt class="docutils literal">dont_have</tt> message. The dont have
message is an extension to allow peers to advertise that the
no longer has a piece they previously had.</td>
</tr>
<tr><td>111</td>
<td>requires_ssl_connection</td>
<td>The peer tried to connect to an SSL torrent without connecting
over SSL.</td>
</tr>
<tr><td>112</td>
<td>invalid_ssl_cert</td>
<td>The peer tried to connect to a torrent with a certificate
for a different torrent.</td>
</tr>
</tbody>
</table>
<p>NAT-PMP errors:</p>
<table border="1" class="docutils">
<colgroup>
<col width="5%" />
<col width="37%" />
<col width="58%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">code</th>
<th class="head">symbol</th>
<th class="head">description</th>
</tr>
</thead>
<tbody valign="top">
<tr><td>120</td>
<td>unsupported_protocol_version</td>
<td>The NAT-PMP router responded with an unsupported protocol version</td>
</tr>
<tr><td>121</td>
<td>natpmp_not_authorized</td>
<td>You are not authorized to map ports on this NAT-PMP router</td>
</tr>
<tr><td>122</td>
<td>network_failure</td>
<td>The NAT-PMP router failed because of a network failure</td>
</tr>
<tr><td>123</td>
<td>no_resources</td>
<td>The NAT-PMP router failed because of lack of resources</td>
</tr>
<tr><td>124</td>
<td>unsupported_opcode</td>
<td>The NAT-PMP router failed because an unsupported opcode was sent</td>
</tr>
</tbody>
</table>
<p>fastresume data errors:</p>
<table border="1" class="docutils">
<colgroup>
<col width="5%" />
<col width="37%" />
<col width="58%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">code</th>
<th class="head">symbol</th>
<th class="head">description</th>
</tr>
</thead>
<tbody valign="top">
<tr><td>130</td>
<td>missing_file_sizes</td>
<td>The resume data file is missing the 'file sizes' entry</td>
</tr>
<tr><td>131</td>
<td>no_files_in_resume_data</td>
<td>The resume data file 'file sizes' entry is empty</td>
</tr>
<tr><td>132</td>
<td>missing_pieces</td>
<td>The resume data file is missing the 'pieces' and 'slots' entry</td>
</tr>
<tr><td>133</td>
<td>mismatching_number_of_files</td>
<td>The number of files in the resume data does not match the number
of files in the torrent</td>
</tr>
<tr><td>134</td>
<td>mismatching_files_size</td>
<td>One of the files on disk has a different size than in the fast
resume file</td>
</tr>
<tr><td>135</td>
<td>mismatching_file_timestamp</td>
<td>One of the files on disk has a different timestamp than in the
fast resume file</td>
</tr>
<tr><td>136</td>
<td>not_a_dictionary</td>
<td>The resume data file is not a dictionary</td>
</tr>
<tr><td>137</td>
<td>invalid_blocks_per_piece</td>
<td>The 'blocks per piece' entry is invalid in the resume data file</td>
</tr>
<tr><td>138</td>
<td>missing_slots</td>
<td>The resume file is missing the 'slots' entry, which is required
for torrents with compact allocation</td>
</tr>
<tr><td>139</td>
<td>too_many_slots</td>
<td>The resume file contains more slots than the torrent</td>
</tr>
<tr><td>140</td>
<td>invalid_slot_list</td>
<td>The 'slot' entry is invalid in the resume data</td>
</tr>
<tr><td>141</td>
<td>invalid_piece_index</td>
<td>One index in the 'slot' list is invalid</td>
</tr>
<tr><td>142</td>
<td>pieces_need_reorder</td>
<td>The pieces on disk needs to be re-ordered for the specified
allocation mode. This happens if you specify sparse allocation
and the files on disk are using compact storage. The pieces needs
to be moved to their right position</td>
</tr>
</tbody>
</table>
<p>HTTP errors:</p>
<table border="1" class="docutils">
<colgroup>
<col width="5%" />
<col width="37%" />
<col width="58%" />
</colgroup>
<tbody valign="top">
<tr><td>150</td>
<td>http_parse_error</td>
<td>The HTTP header was not correctly formatted</td>
</tr>
<tr><td>151</td>
<td>http_missing_location</td>
<td>The HTTP response was in the 300-399 range but lacked a location
header</td>
</tr>
<tr><td>152</td>
<td>http_failed_decompress</td>
<td>The HTTP response was encoded with gzip or deflate but
decompressing it failed</td>
</tr>
</tbody>
</table>
<p>I2P errors:</p>
<table border="1" class="docutils">
<colgroup>
<col width="5%" />
<col width="37%" />
<col width="58%" />
</colgroup>
<tbody valign="top">
<tr><td>160</td>
<td>no_i2p_router</td>
<td>The URL specified an i2p address, but no i2p router is configured</td>
</tr>
</tbody>
</table>
<p>tracker errors:</p>
<table border="1" class="docutils">
<colgroup>
<col width="5%" />
<col width="37%" />
<col width="58%" />
</colgroup>
<tbody valign="top">
<tr><td>170</td>
<td>scrape_not_available</td>
<td>The tracker URL doesn't support transforming it into a scrape
URL. i.e. it doesn't contain &quot;announce.</td>
</tr>
<tr><td>171</td>
<td>invalid_tracker_response</td>
<td>invalid tracker response</td>
</tr>
<tr><td>172</td>
<td>invalid_peer_dict</td>
<td>invalid peer dictionary entry. Not a dictionary</td>
</tr>
<tr><td>173</td>
<td>tracker_failure</td>
<td>tracker sent a failure message</td>
</tr>
<tr><td>174</td>
<td>invalid_files_entry</td>
<td>missing or invalid 'files' entry</td>
</tr>
<tr><td>175</td>
<td>invalid_hash_entry</td>
<td>missing or invalid 'hash' entry</td>
</tr>
<tr><td>176</td>
<td>invalid_peers_entry</td>
<td>missing or invalid 'peers' and 'peers6' entry</td>
</tr>
<tr><td>177</td>
<td>invalid_tracker_response_length</td>
<td>udp tracker response packet has invalid size</td>
</tr>
<tr><td>178</td>
<td>invalid_tracker_transaction_id</td>
<td>invalid transaction id in udp tracker response</td>
</tr>
<tr><td>179</td>
<td>invalid_tracker_action</td>
<td>invalid action field in udp tracker response</td>
</tr>
<tr><td>190</td>
<td>expected_string</td>
<td>expected string in bencoded string</td>
</tr>
<tr><td>191</td>
<td>expected_colon</td>
<td>expected colon in bencoded string</td>
</tr>
<tr><td>192</td>
<td>unexpected_eof</td>
<td>unexpected end of file in bencoded string</td>
</tr>
<tr><td>193</td>
<td>expected_value</td>
<td>expected value (list, dict, int or string) in bencoded string</td>
</tr>
<tr><td>194</td>
<td>depth_exceeded</td>
<td>bencoded recursion depth limit exceeded</td>
</tr>
<tr><td>195</td>
<td>item_limit_exceeded</td>
<td>bencoded item count limit exceeded</td>
</tr>
</tbody>
</table>
<p>The names of these error codes are declared in then <tt class="docutils literal"><span class="pre">libtorrent::errors</span></tt> namespace.</p>
<p>There is also another error category, <tt class="docutils literal"><span class="pre">libtorrent::upnp_category</span></tt>, defining errors
retrned by UPnP routers. Here's a (possibly incomplete) list of UPnP error codes:</p>
<table border="1" class="docutils">
<colgroup>
<col width="6%" />
<col width="41%" />
<col width="53%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">code</th>
<th class="head">symbol</th>
<th class="head">description</th>
</tr>
</thead>
<tbody valign="top">
<tr><td>0</td>
<td>no_error</td>
<td>No error</td>
</tr>
<tr><td>402</td>
<td>invalid_argument</td>
<td>One of the arguments in the request is invalid</td>
</tr>
<tr><td>501</td>
<td>action_failed</td>
<td>The request failed</td>
</tr>
<tr><td>714</td>
<td>value_not_in_array</td>
<td>The specified value does not exist in the array</td>
</tr>
<tr><td>715</td>
<td>source_ip_cannot_be_wildcarded</td>
<td>The source IP address cannot be wild-carded, but
must be fully specified</td>
</tr>
<tr><td>716</td>
<td>external_port_cannot_be_wildcarded</td>
<td>The external port cannot be wildcarded, but must
be specified</td>
</tr>
<tr><td>718</td>
<td>port_mapping_conflict</td>
<td>The port mapping entry specified conflicts with a
mapping assigned previously to another client</td>
</tr>
<tr><td>724</td>
<td>internal_port_must_match_external</td>
<td>Internal and external port value must be the same</td>
</tr>
<tr><td>725</td>
<td>only_permanent_leases_supported</td>
<td>The NAT implementation only supports permanent
lease times on port mappings</td>
</tr>
<tr><td>726</td>
<td>remote_host_must_be_wildcard</td>
<td>RemoteHost must be a wildcard and cannot be a
specific IP addres or DNS name</td>
</tr>
<tr><td>727</td>
<td>external_port_must_be_wildcard</td>
<td>ExternalPort must be a wildcard and cannot be a
specific port</td>
</tr>
</tbody>
</table>
<p>The UPnP errors are declared in the <tt class="docutils literal"><span class="pre">libtorrent::upnp_errors</span></tt> namespace.</p>
<p>HTTP errors are reported in the <tt class="docutils literal"><span class="pre">libtorrent::http_category</span></tt>, with error code enums in
the <tt class="docutils literal"><span class="pre">libtorrent::errors</span></tt> namespace.</p>
<table border="1" class="docutils">
<colgroup>
<col width="13%" />
<col width="87%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">code</th>
<th class="head">symbol</th>
</tr>
</thead>
<tbody valign="top">
<tr><td>100</td>
<td>cont</td>
</tr>
<tr><td>200</td>
<td>ok</td>
</tr>
<tr><td>201</td>
<td>created</td>
</tr>
<tr><td>202</td>
<td>accepted</td>
</tr>
<tr><td>204</td>
<td>no_content</td>
</tr>
<tr><td>300</td>
<td>multiple_choices</td>
</tr>
<tr><td>301</td>
<td>moved_permanently</td>
</tr>
<tr><td>302</td>
<td>moved_temporarily</td>
</tr>
<tr><td>304</td>
<td>not_modified</td>
</tr>
<tr><td>400</td>
<td>bad_request</td>
</tr>
<tr><td>401</td>
<td>unauthorized</td>
</tr>
<tr><td>403</td>
<td>forbidden</td>
</tr>
<tr><td>404</td>
<td>not_found</td>
</tr>
<tr><td>500</td>
<td>internal_server_error</td>
</tr>
<tr><td>501</td>
<td>not_implemented</td>
</tr>
<tr><td>502</td>
<td>bad_gateway</td>
</tr>
<tr><td>503</td>
<td>service_unavailable</td>
</tr>
</tbody>
</table>
<div class="section" id="translating-error-codes">
<h2>translating error codes</h2>
<p>The error_code::message() function will typically return a localized error string,
for system errors. That is, errors that belong to the generic or system category.</p>
<p>Errors that belong to the libtorrent error category are not localized however, they
are only available in english. In order to translate libtorrent errors, compare the
error category of the <tt class="docutils literal">error_code</tt> object against <tt class="docutils literal"><span class="pre">libtorrent::get_libtorrent_category()</span></tt>,
and if matches, you know the error code refers to the list above. You can provide
your own mapping from error code to string, which is localized. In this case, you
cannot rely on <tt class="docutils literal"><span class="pre">error_code::message()</span></tt> to generate your strings.</p>
<p>The numeric values of the errors are part of the API and will stay the same, although
new error codes may be appended at the end.</p>
<p>Here's a simple example of how to translate error codes:</p>
<pre class="literal-block">
std::string error_code_to_string(boost::system::error_code const&amp; ec)
{
        if (ec.category() != libtorrent::get_libtorrent_category())
        {
                return ec.message();
        }
        // the error is a libtorrent error

        int code = ec.value();
        static const char const* swedish[] =
        {
                &quot;inget fel&quot;,
                &quot;en fil i torrenten kolliderar med en fil fran en annan torrent&quot;,
                &quot;hash check misslyckades&quot;,
                &quot;torrent filen ar inte en dictionary&quot;,
                &quot;'info'-nyckeln saknas eller ar korrupt i torrentfilen&quot;,
                &quot;'info'-faltet ar inte en dictionary&quot;,
                &quot;'piece length' faltet saknas eller ar korrupt i torrentfilen&quot;,
                &quot;torrentfilen saknar namnfaltet&quot;,
                &quot;ogiltigt namn i torrentfilen (kan vara en attack)&quot;,
                // ... more strings here
        };

        // use the default error string in case we don't have it
        // in our translated list
        if (code &lt; 0 || code &gt;= sizeof(swedish)/sizeof(swedish[0]))
                return ec.message();

        return swedish[code];
}
</pre>
</div>
</div>
<div class="section" id="storage-interface">
<h1>storage_interface</h1>
<p>The storage interface is a pure virtual class that can be implemented to
customize how and where data for a torrent is stored. The default storage
implementation uses regular files in the filesystem, mapping the files in the
torrent in the way one would assume a torrent is saved to disk. Implementing
your own storage interface makes it possible to store all data in RAM, or in
some optimized order on disk (the order the pieces are received for instance),
or saving multifile torrents in a single file in order to be able to take
advantage of optimized disk-I/O.</p>
<p>It is also possible to write a thin class that uses the default storage but
modifies some particular behavior, for instance encrypting the data before
it's written to disk, and decrypting it when it's read again.</p>
<p>The storage interface is based on slots, each slot is 'piece_size' number
of bytes. All access is done by writing and reading whole or partial
slots. One slot is one piece in the torrent, but the data in the slot
does not necessarily correspond to the piece with the same index (in
compact allocation mode it won't).</p>
<p>libtorrent comes with two built-in storage implementations; <tt class="docutils literal">default_storage</tt>
and <tt class="docutils literal">disabled_storage</tt>. Their constructor functions are called <tt class="docutils literal">default_storage_constructor</tt>
and <tt class="docutils literal">disabled_storage_constructor</tt> respectively. The disabled storage does
just what it sounds like. It throws away data that's written, and it
reads garbage. It's useful mostly for benchmarking and profiling purpose.</p>
<p>The interface looks like this:</p>
<pre class="literal-block">
struct storage_interface
{
        virtual bool initialize(bool allocate_files) = 0;
        virtual bool has_any_file() = 0;
        virtual void hint_read(int slot, int offset, int len);
        virtual int readv(file::iovec_t const* bufs, int slot, int offset, int num_bufs) = 0;
        virtual int writev(file::iovec_t const* bufs, int slot, int offset, int num_bufs) = 0;
        virtual int sparse_end(int start) const;
        virtual bool move_storage(fs::path save_path) = 0;
        virtual bool verify_resume_data(lazy_entry const&amp; rd, error_code&amp; error) = 0;
        virtual bool write_resume_data(entry&amp; rd) const = 0;
        virtual bool move_slot(int src_slot, int dst_slot) = 0;
        virtual bool swap_slots(int slot1, int slot2) = 0;
        virtual bool swap_slots3(int slot1, int slot2, int slot3) = 0;
        virtual bool rename_file(int file, std::string const&amp; new_name) = 0;
        virtual bool release_files() = 0;
        virtual bool delete_files() = 0;
        virtual void finalize_file(int index) {}
        virtual ~storage_interface() {}

        // non virtual functions

        disk_buffer_pool* disk_pool();
        void set_error(std::string const&amp; file, error_code const&amp; ec) const;
        error_code const&amp; error() const;
        std::string const&amp; error_file() const;
        void clear_error();
};
</pre>
<div class="section" id="initialize">
<h2>initialize()</h2>
<blockquote>
<pre class="literal-block">
bool initialize(bool allocate_files) = 0;
</pre>
</blockquote>
<p>This function is called when the storage is to be initialized. The default storage
will create directories and empty files at this point. If <tt class="docutils literal">allocate_files</tt> is true,
it will also <tt class="docutils literal">ftruncate</tt> all files to their target size.</p>
<p>Returning <tt class="docutils literal">true</tt> indicates an error occurred.</p>
</div>
<div class="section" id="has-any-file">
<h2>has_any_file()</h2>
<blockquote>
<pre class="literal-block">
virtual bool has_any_file() = 0;
</pre>
</blockquote>
<p>This function is called when first checking (or re-checking) the storage for a torrent.
It should return true if any of the files that is used in this storage exists on disk.
If so, the storage will be checked for existing pieces before starting the download.</p>
</div>
<div class="section" id="hint-read">
<h2>hint_read()</h2>
<blockquote>
<pre class="literal-block">
void hint_read(int slot, int offset, int len);
</pre>
</blockquote>
<p>This function is called when a read job is queued. It gives the storage wrapper an
opportunity to hint the operating system about this coming read. For instance, the
storage may call <tt class="docutils literal">posix_fadvise(POSIX_FADV_WILLNEED)</tt> or <tt class="docutils literal">fcntl(F_RDADVISE)</tt>.</p>
</div>
<div class="section" id="readv-writev">
<h2>readv() writev()</h2>
<blockquote>
<pre class="literal-block">
int readv(file::iovec_t const* buf, int slot, int offset, int num_bufs) = 0;
int write(const char* buf, int slot, int offset, int size) = 0;
</pre>
</blockquote>
<p>These functions should read or write the data in or to the given <tt class="docutils literal">slot</tt> at the given <tt class="docutils literal">offset</tt>.
It should read or write <tt class="docutils literal">num_bufs</tt> buffers sequentially, where the size of each buffer
is specified in the buffer array <tt class="docutils literal">bufs</tt>. The <a class="reference external" href="file::iovec_t">file::iovec_t</a> type has the following members:</p>
<pre class="literal-block">
struct iovec_t
{
        void* iov_base;
        size_t iov_len;
};
</pre>
<p>The return value is the number of bytes actually read or written, or -1 on failure. If
it returns -1, the error code is expected to be set to</p>
<p>Every buffer in <tt class="docutils literal">bufs</tt> can be assumed to be page aligned and be of a page aligned size,
except for the last buffer of the torrent. The allocated buffer can be assumed to fit a
fully page aligned number of bytes though. This is useful when reading and writing the
last piece of a file in unbuffered mode.</p>
<p>The <tt class="docutils literal">offset</tt> is aligned to 16 kiB boundries  <em>most of the time</em>, but there are rare
exceptions when it's not. Specifically if the read cache is disabled/or full and a
client requests unaligned data, or the file itself is not aligned in the torrent.
Most clients request aligned data.</p>
</div>
<div class="section" id="sparse-end">
<h2>sparse_end()</h2>
<blockquote>
<pre class="literal-block">
int sparse_end(int start) const;
</pre>
</blockquote>
<p>This function is optional. It is supposed to return the first piece, starting at
<tt class="docutils literal">start</tt> that is fully contained within a data-region on disk (i.e. non-sparse
region). The purpose of this is to skip parts of files that can be known to contain
zeros when checking files.</p>
</div>
<div class="section" id="id10">
<h2>move_storage()</h2>
<blockquote>
<pre class="literal-block">
bool move_storage(fs::path save_path) = 0;
</pre>
</blockquote>
<p>This function should move all the files belonging to the storage to the new save_path.
The default storage moves the single file or the directory of the torrent.</p>
<p>Before moving the files, any open file handles may have to be closed, like
<tt class="docutils literal">release_files()</tt>.</p>
<p>Returning <tt class="docutils literal">false</tt> indicates an error occurred.</p>
</div>
<div class="section" id="verify-resume-data">
<h2>verify_resume_data()</h2>
<blockquote>
<pre class="literal-block">
bool verify_resume_data(lazy_entry const&amp; rd, error_code&amp; error) = 0;
</pre>
</blockquote>
<p>This function should verify the resume data <tt class="docutils literal">rd</tt> with the files
on disk. If the resume data seems to be up-to-date, return true. If
not, set <tt class="docutils literal">error</tt> to a description of what mismatched and return false.</p>
<p>The default storage may compare file sizes and time stamps of the files.</p>
<p>Returning <tt class="docutils literal">false</tt> indicates an error occurred.</p>
</div>
<div class="section" id="write-resume-data">
<h2>write_resume_data()</h2>
<blockquote>
<pre class="literal-block">
bool write_resume_data(entry&amp; rd) const = 0;
</pre>
</blockquote>
<p>This function should fill in resume data, the current state of the
storage, in <tt class="docutils literal">rd</tt>. The default storage adds file timestamps and
sizes.</p>
<p>Returning <tt class="docutils literal">true</tt> indicates an error occurred.</p>
</div>
<div class="section" id="move-slot">
<h2>move_slot()</h2>
<blockquote>
<pre class="literal-block">
bool move_slot(int src_slot, int dst_slot) = 0;
</pre>
</blockquote>
<p>This function should copy or move the data in slot <tt class="docutils literal">src_slot</tt> to
the slot <tt class="docutils literal">dst_slot</tt>. This is only used in compact mode.</p>
<p>If the storage caches slots, this could be implemented more
efficient than reading and writing the data.</p>
<p>Returning <tt class="docutils literal">true</tt> indicates an error occurred.</p>
</div>
<div class="section" id="swap-slots">
<h2>swap_slots()</h2>
<blockquote>
<pre class="literal-block">
bool swap_slots(int slot1, int slot2) = 0;
</pre>
</blockquote>
<p>This function should swap the data in <tt class="docutils literal">slot1</tt> and <tt class="docutils literal">slot2</tt>. The default
storage uses a scratch buffer to read the data into, then moving the other
slot and finally writing back the temporary slot's data</p>
<p>This is only used in compact mode.</p>
<p>Returning <tt class="docutils literal">true</tt> indicates an error occurred.</p>
</div>
<div class="section" id="swap-slots3">
<h2>swap_slots3()</h2>
<blockquote>
<pre class="literal-block">
bool swap_slots3(int slot1, int slot2, int slot3) = 0;
</pre>
</blockquote>
<p>This function should do a 3-way swap, or shift of the slots. <tt class="docutils literal">slot1</tt>
should move to <tt class="docutils literal">slot2</tt>, which should be moved to <tt class="docutils literal">slot3</tt> which in turn
should be moved to <tt class="docutils literal">slot1</tt>.</p>
<p>This is only used in compact mode.</p>
<p>Returning <tt class="docutils literal">true</tt> indicates an error occurred.</p>
</div>
<div class="section" id="id11">
<h2>rename_file()</h2>
<blockquote>
<pre class="literal-block">
bool rename_file(int file, std::string const&amp; new_name) = 0;
</pre>
</blockquote>
<p>Rename file with index <tt class="docutils literal">file</tt> to the thame <tt class="docutils literal">new_name</tt>. If there is an error,
<tt class="docutils literal">true</tt> should be returned.</p>
</div>
<div class="section" id="release-files">
<h2>release_files()</h2>
<blockquote>
<pre class="literal-block">
bool release_files() = 0;
</pre>
</blockquote>
<p>This function should release all the file handles that it keeps open to files
belonging to this storage. The default implementation just calls
<tt class="docutils literal"><span class="pre">file_pool::release_files(this)</span></tt>.</p>
<p>Returning <tt class="docutils literal">true</tt> indicates an error occurred.</p>
</div>
<div class="section" id="delete-files">
<h2>delete_files()</h2>
<blockquote>
<pre class="literal-block">
bool delete_files() = 0;
</pre>
</blockquote>
<p>This function should delete all files and directories belonging to this storage.</p>
<p>Returning <tt class="docutils literal">true</tt> indicates an error occurred.</p>
<p>The <tt class="docutils literal">disk_buffer_pool</tt> is used to allocate and free disk buffers. It has the
following members:</p>
<pre class="literal-block">
struct disk_buffer_pool : boost::noncopyable
{
        char* allocate_buffer(char const* category);
        void free_buffer(char* buf);

        char* allocate_buffers(int blocks, char const* category);
        void free_buffers(char* buf, int blocks);

        int block_size() const { return m_block_size; }

        void release_memory();
};
</pre>
</div>
<div class="section" id="finalize-file">
<h2>finalize_file()</h2>
<blockquote>
<pre class="literal-block">
virtual void finalize_file(int index);
</pre>
</blockquote>
<p>This function is called each time a file is completely downloaded. The
storage implementation can perform last operations on a file. The file will
not be opened for writing after this.</p>
<p><tt class="docutils literal">index</tt> is the index of the file that completed.</p>
<p>On windows the default storage implementation clears the sparse file flag
on the specified file.</p>
</div>
<div class="section" id="example">
<h2>example</h2>
<p>This is an example storage implementation that stores all pieces in a <tt class="docutils literal"><span class="pre">std::map</span></tt>,
i.e. in RAM. It's not necessarily very useful in practice, but illustrates the
basics of implementing a custom storage.</p>
<pre class="literal-block">
struct temp_storage : storage_interface
{
        temp_storage(file_storage const&amp; fs) : m_files(fs) {}
        virtual bool initialize(bool allocate_files) { return false; }
        virtual bool has_any_file() { return false; }
        virtual int read(char* buf, int slot, int offset, int size)
        {
                std::map&lt;int, std::vector&lt;char&gt; &gt;::const_iterator i = m_file_data.find(slot);
                if (i == m_file_data.end()) return 0;
                int available = i-&gt;second.size() - offset;
                if (available &lt;= 0) return 0;
                if (available &gt; size) available = size;
                memcpy(buf, &amp;i-&gt;second[offset], available);
                return available;
        }
        virtual int write(const char* buf, int slot, int offset, int size)
        {
                std::vector&lt;char&gt;&amp; data = m_file_data[slot];
                if (data.size() &lt; offset + size) data.resize(offset + size);
                std::memcpy(&amp;data[offset], buf, size);
                return size;
        }
        virtual bool rename_file(int file, std::string const&amp; new_name)
        { assert(false); return false; }
        virtual bool move_storage(std::string const&amp; save_path) { return false; }
        virtual bool verify_resume_data(lazy_entry const&amp; rd, error_code&amp; error) { return false; }
        virtual bool write_resume_data(entry&amp; rd) const { return false; }
        virtual bool move_slot(int src_slot, int dst_slot) { assert(false); return false; }
        virtual bool swap_slots(int slot1, int slot2) { assert(false); return false; }
        virtual bool swap_slots3(int slot1, int slot2, int slot3) { assert(false); return false; }
        virtual size_type physical_offset(int slot, int offset)
        { return slot * m_files.piece_length() + offset; };
        virtual sha1_hash hash_for_slot(int slot, partial_hash&amp; ph, int piece_size)
        {
                int left = piece_size - ph.offset;
                assert(left &gt;= 0);
                if (left &gt; 0)
                {
                        std::vector&lt;char&gt;&amp; data = m_file_data[slot];
                        // if there are padding files, those blocks will be considered
                        // completed even though they haven't been written to the storage.
                        // in this case, just extend the piece buffer to its full size
                        // and fill it with zeroes.
                        if (data.size() &lt; piece_size) data.resize(piece_size, 0);
                        ph.h.update(&amp;data[ph.offset], left);
                }
                return ph.h.final();
        }
        virtual bool release_files() { return false; }
        virtual bool delete_files() { return false; }

        std::map&lt;int, std::vector&lt;char&gt; &gt; m_file_data;
        file_storage m_files;
};

storage_interface* temp_storage_constructor(
        file_storage const&amp; fs, file_storage const* mapped
        , std::string const&amp; path, file_pool&amp; fp
        , std::vector&lt;boost::uint8_t&gt; const&amp; prio)
{
        return new temp_storage(fs);
}
</pre>
</div>
</div>
<div class="section" id="magnet-links">
<h1>magnet links</h1>
<p>Magnet links are URIs that includes an info-hash, a display name and optionally
a tracker url. The idea behind magnet links is that an end user can click on a
link in a browser and have it handled by a bittorrent application, to start a
download, without any .torrent file.</p>
<p>The format of the magnet URI is:</p>
<p><strong>magnet:?xt=urn:btih:</strong> <em>Base32 encoded info-hash</em> [ <strong>&amp;dn=</strong> <em>name of download</em> ] [ <strong>&amp;tr=</strong> <em>tracker URL</em> ]*</p>
</div>
<div class="section" id="queuing">
<h1>queuing</h1>
<p>libtorrent supports <em>queuing</em>. Which means it makes sure that a limited number of
torrents are being downloaded at any given time, and once a torrent is completely
downloaded, the next in line is started.</p>
<p>Torrents that are <em>auto managed</em> are subject to the queuing and the active torrents
limits. To make a torrent auto managed, set <tt class="docutils literal">auto_managed</tt> to true when adding the
torrent (see <a class="reference internal" href="#async-add-torrent-add-torrent">async_add_torrent() add_torrent()</a>).</p>
<p>The limits of the number of downloading and seeding torrents are controlled via
<tt class="docutils literal">active_downloads</tt>, <tt class="docutils literal">active_seeds</tt> and <tt class="docutils literal">active_limit</tt> in <a class="reference internal" href="#session-settings">session_settings</a>.
These limits takes non auto managed torrents into account as well. If there are
more non-auto managed torrents being downloaded than the <tt class="docutils literal">active_downloads</tt>
setting, any auto managed torrents will be queued until torrents are removed so
that the number drops below the limit.</p>
<p>The default values are 8 active downloads and 5 active seeds.</p>
<p>At a regular interval, torrents are checked if there needs to be any re-ordering of
which torrents are active and which are queued. This interval can be controlled via
<tt class="docutils literal">auto_manage_interval</tt> in <a class="reference internal" href="#session-settings">session_settings</a>. It defaults to every 30 seconds.</p>
<p>For queuing to work, resume data needs to be saved and restored for all torrents.
See <a class="reference internal" href="#save-resume-data">save_resume_data()</a>.</p>
<div class="section" id="downloading">
<h2>downloading</h2>
<p>Torrents that are currently being downloaded or incomplete (with bytes still to download)
are queued. The torrents in the front of the queue are started to be actively downloaded
and the rest are ordered with regards to their queue position. Any newly added torrent
is placed at the end of the queue. Once a torrent is removed or turns into a seed, its
queue position is -1 and all torrents that used to be after it in the queue, decreases their
position in order to fill the gap.</p>
<p>The queue positions are always in a sequence without any gaps.</p>
<p>Lower queue position means closer to the front of the queue, and will be started sooner than
torrents with higher queue positions.</p>
<p>To query a torrent for its position in the queue, or change its position, see:
<a class="reference internal" href="#queue-position-queue-position-up-queue-position-down-queue-position-top-queue-position-bottom">queue_position() queue_position_up() queue_position_down() queue_position_top() queue_position_bottom()</a>.</p>
</div>
<div class="section" id="seeding">
<h2>seeding</h2>
<p>Auto managed seeding torrents are rotated, so that all of them are allocated a fair
amount of seeding. Torrents with fewer completed <em>seed cycles</em> are prioritized for
seeding. A seed cycle is completed when a torrent meets either the share ratio limit
(uploaded bytes / downloaded bytes), the share time ratio (time seeding / time
downloaing) or seed time limit (time seeded).</p>
<p>The relevant settings to control these limits are <tt class="docutils literal">share_ratio_limit</tt>,
<tt class="docutils literal">seed_time_ratio_limit</tt> and <tt class="docutils literal">seed_time_limit</tt> in <a class="reference internal" href="#session-settings">session_settings</a>.</p>
</div>
</div>
<div class="section" id="fast-resume">
<h1>fast resume</h1>
<p>The fast resume mechanism is a way to remember which pieces are downloaded
and where they are put between sessions. You can generate fast resume data by
calling <a class="reference internal" href="#save-resume-data">save_resume_data()</a> on <a class="reference internal" href="#torrent-handle">torrent_handle</a>. You can
then save this data to disk and use it when resuming the torrent. libtorrent
will not check the piece hashes then, and rely on the information given in the
fast-resume data. The fast-resume data also contains information about which
blocks, in the unfinished pieces, were downloaded, so it will not have to
start from scratch on the partially downloaded pieces.</p>
<p>To use the fast-resume data you simply give it to <a class="reference internal" href="#async-add-torrent-add-torrent">async_add_torrent() add_torrent()</a>, and it
will skip the time consuming checks. It may have to do the checking anyway, if
the fast-resume data is corrupt or doesn't fit the storage for that torrent,
then it will not trust the fast-resume data and just do the checking.</p>
<div class="section" id="file-format">
<h2>file format</h2>
<p>The file format is a bencoded dictionary containing the following fields:</p>
<table border="1" class="docutils">
<colgroup>
<col width="30%" />
<col width="70%" />
</colgroup>
<tbody valign="top">
<tr><td><tt class="docutils literal"><span class="pre">file-format</span></tt></td>
<td>string: &quot;libtorrent resume file&quot;</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">file-version</span></tt></td>
<td>integer: 1</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">info-hash</span></tt></td>
<td>string, the info hash of the torrent this data is saved for.</td>
</tr>
<tr><td><tt class="docutils literal">blocks per piece</tt></td>
<td>integer, the number of blocks per piece. Must be: piece_size
/ (16 * 1024). Clamped to be within the range [1, 256]. It
is the number of blocks per (normal sized) piece. Usually
each block is 16 * 1024 bytes in size. But if piece size is
greater than 4 megabytes, the block size will increase.</td>
</tr>
<tr><td><tt class="docutils literal">pieces</tt></td>
<td>A string with piece flags, one character per piece.
Bit 1 means we have that piece.
Bit 2 means we have verified that this piece is correct.
This only applies when the torrent is in seed_mode.</td>
</tr>
<tr><td><tt class="docutils literal">slots</tt></td>
<td><p class="first">list of integers. The list maps slots to piece indices. It
tells which piece is on which slot. If piece index is -2 it
means it is free, that there's no piece there. If it is -1,
means the slot isn't allocated on disk yet. The pieces have
to meet the following requirement:</p>
<p class="last">If there's a slot at the position of the piece index,
the piece must be located in that slot.</p>
</td>
</tr>
<tr><td><tt class="docutils literal">total_uploaded</tt></td>
<td>integer. The number of bytes that have been uploaded in
total for this torrent.</td>
</tr>
<tr><td><tt class="docutils literal">total_downloaded</tt></td>
<td>integer. The number of bytes that have been downloaded in
total for this torrent.</td>
</tr>
<tr><td><tt class="docutils literal">active_time</tt></td>
<td>integer. The number of seconds this torrent has been active.
i.e. not paused.</td>
</tr>
<tr><td><tt class="docutils literal">seeding_time</tt></td>
<td>integer. The number of seconds this torrent has been active
and seeding.</td>
</tr>
<tr><td><tt class="docutils literal">num_seeds</tt></td>
<td>integer. An estimate of the number of seeds on this torrent
when the resume data was saved. This is scrape data or based
on the peer list if scrape data is unavailable.</td>
</tr>
<tr><td><tt class="docutils literal">num_downloaders</tt></td>
<td>integer. An estimate of the number of downloaders on this
torrent when the resume data was last saved. This is used as
an initial estimate until we acquire up-to-date scrape info.</td>
</tr>
<tr><td><tt class="docutils literal">upload_rate_limit</tt></td>
<td>integer. In case this torrent has a per-torrent upload rate
limit, this is that limit. In bytes per second.</td>
</tr>
<tr><td><tt class="docutils literal">download_rate_limit</tt></td>
<td>integer. The download rate limit for this torrent in case
one is set, in bytes per second.</td>
</tr>
<tr><td><tt class="docutils literal">max_connections</tt></td>
<td>integer. The max number of peer connections this torrent
may have, if a limit is set.</td>
</tr>
<tr><td><tt class="docutils literal">max_uploads</tt></td>
<td>integer. The max number of unchoked peers this torrent may
have, if a limit is set.</td>
</tr>
<tr><td><tt class="docutils literal">seed_mode</tt></td>
<td>integer. 1 if the torrent is in seed mode, 0 otherwise.</td>
</tr>
<tr><td><tt class="docutils literal">file_priority</tt></td>
<td>list of integers. One entry per file in the torrent. Each
entry is the priority of the file with the same index.</td>
</tr>
<tr><td><tt class="docutils literal">piece_priority</tt></td>
<td>string of bytes. Each byte is interpreted as an integer and
is the priority of that piece.</td>
</tr>
<tr><td><tt class="docutils literal">auto_managed</tt></td>
<td>integer. 1 if the torrent is auto managed, otherwise 0.</td>
</tr>
<tr><td><tt class="docutils literal">sequential_download</tt></td>
<td>integer. 1 if the torrent is in sequential download mode,
0 otherwise.</td>
</tr>
<tr><td><tt class="docutils literal">paused</tt></td>
<td>integer. 1 if the torrent is paused, 0 otherwise.</td>
</tr>
<tr><td><tt class="docutils literal">trackers</tt></td>
<td>list of lists of strings. The top level list lists all
tracker tiers. Each second level list is one tier of
trackers.</td>
</tr>
<tr><td><tt class="docutils literal">mapped_files</tt></td>
<td>list of strings. If any file in the torrent has been
renamed, this entry contains a list of all the filenames.
In the same order as in the torrent file.</td>
</tr>
<tr><td><tt class="docutils literal"><span class="pre">url-list</span></tt></td>
<td>list of strings. List of url-seed URLs used by this torrent.
The urls are expected to be properly encoded and not contain
any illegal url characters.</td>
</tr>
<tr><td><tt class="docutils literal">httpseeds</tt></td>
<td>list of strings. List of httpseed URLs used by this torrent.
The urls are expected to be properly encoded and not contain
any illegal url characters.</td>
</tr>
<tr><td><tt class="docutils literal">merkle tree</tt></td>
<td>string. In case this torrent is a merkle torrent, this is a
string containing the entire merkle tree, all nodes,
including the root and all leaves. The tree is not
necessarily complete, but complete enough to be able to send
any piece that we have, indicated by the have bitmask.</td>
</tr>
<tr><td><tt class="docutils literal">peers</tt></td>
<td><p class="first">list of dictionaries. Each dictionary has the following
layout:</p>
<table border="1" class="docutils">
<colgroup>
<col width="18%" />
<col width="82%" />
</colgroup>
<tbody valign="top">
<tr><td><tt class="docutils literal">ip</tt></td>
<td>string, the ip address of the peer. This is
not a binary representation of the ip
address, but the string representation. It
may be an IPv6 string or an IPv4 string.</td>
</tr>
<tr><td><tt class="docutils literal">port</tt></td>
<td>integer, the listen port of the peer</td>
</tr>
</tbody>
</table>
<p class="last">These are the local peers we were connected to when this
fast-resume data was saved.</p>
</td>
</tr>
<tr><td><tt class="docutils literal">unfinished</tt></td>
<td><p class="first">list of dictionaries. Each dictionary represents an
piece, and has the following layout:</p>
<table border="1" class="last docutils">
<colgroup>
<col width="23%" />
<col width="77%" />
</colgroup>
<tbody valign="top">
<tr><td><tt class="docutils literal">piece</tt></td>
<td>integer, the index of the piece this entry
refers to.</td>
</tr>
<tr><td><tt class="docutils literal">bitmask</tt></td>
<td>string, a binary bitmask representing the
blocks that have been downloaded in this
piece.</td>
</tr>
<tr><td><tt class="docutils literal">adler32</tt></td>
<td>The adler32 checksum of the data in the
blocks specified by <tt class="docutils literal">bitmask</tt>.</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr><td><tt class="docutils literal">file sizes</tt></td>
<td>list where each entry corresponds to a file in the file list
in the metadata. Each entry has a list of two values, the
first value is the size of the file in bytes, the second
is the time stamp when the last time someone wrote to it.
This information is used to compare with the files on disk.
All the files must match exactly this information in order
to consider the resume data as current. Otherwise a full
re-check is issued.</td>
</tr>
<tr><td><tt class="docutils literal">allocation</tt></td>
<td>The allocation mode for the storage. Can be either <tt class="docutils literal">full</tt>
or <tt class="docutils literal">compact</tt>. If this is full, the file sizes and
timestamps are disregarded. Pieces are assumed not to have
moved around even if the files have been modified after the
last resume data checkpoint.</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="section" id="storage-allocation">
<h1>storage allocation</h1>
<p>There are two modes in which storage (files on disk) are allocated in libtorrent.</p>
<ol class="arabic simple">
<li>The traditional <em>full allocation</em> mode, where the entire files are filled up with
zeros before anything is downloaded. libtorrent will look for sparse files support
in the filesystem that is used for storage, and use sparse files or file system
zero fill support if present. This means that on NTFS, full allocation mode will
only allocate storage for the downloaded pieces.</li>
<li>The <em>sparse allocation</em>, sparse files are used, and pieces are downloaded directly
to where they belong. This is the recommended (and default) mode.</li>
</ol>
<p>In previous versions of libtorrent, a 3rd mode was supported, <em>compact allocation</em>.
Support for this is deprecated and will be removed in future versions of libtorrent.
It's still described in here for completeness.</p>
<p>The allocation mode is selected when a torrent is started. It is passed as an
argument to <tt class="docutils literal"><span class="pre">session::add_torrent()</span></tt> (see <a class="reference internal" href="#async-add-torrent-add-torrent">async_add_torrent() add_torrent()</a>).</p>
<p>The decision to use full allocation or compact allocation typically depends on whether
any files have priority 0 and if the filesystem supports sparse files.</p>
<div class="section" id="sparse-allocation">
<h2>sparse allocation</h2>
<p>On filesystems that supports sparse files, this allocation mode will only use
as much space as has been downloaded.</p>
<blockquote>
<ul class="simple">
<li>It does not require an allocation pass on startup.</li>
<li>It supports skipping files (setting prioirty to 0 to not download).</li>
<li>Fast resume data will remain valid even when file time stamps are out of date.</li>
</ul>
</blockquote>
</div>
<div class="section" id="full-allocation">
<h2>full allocation</h2>
<p>When a torrent is started in full allocation mode, the disk-io thread
will make sure that the entire storage is allocated, and fill any gaps with zeros.
This will be skipped if the filesystem supports sparse files or automatic zero filling.
It will of course still check for existing pieces and fast resume data. The main
drawbacks of this mode are:</p>
<blockquote>
<ul class="simple">
<li>It may take longer to start the torrent, since it will need to fill the files
with zeros on some systems. This delay is linearly dependent on the size of
the download.</li>
<li>The download may occupy unnecessary disk space between download sessions. In case
sparse files are not supported.</li>
<li>Disk caches usually perform extremely poorly with random access to large files
and may slow down a download considerably.</li>
</ul>
</blockquote>
<p>The benefits of this mode are:</p>
<blockquote>
<ul class="simple">
<li>Downloaded pieces are written directly to their final place in the files and the
total number of disk operations will be fewer and may also play nicer to
filesystems' file allocation, and reduce fragmentation.</li>
<li>No risk of a download failing because of a full disk during download. Unless
sparse files are being used.</li>
<li>The fast resume data will be more likely to be usable, regardless of crashes or
out of date data, since pieces won't move around.</li>
<li>Can be used with prioritizing files to 0.</li>
</ul>
</blockquote>
</div>
<div class="section" id="compact-allocation">
<h2>compact allocation</h2>
<p>Note that support for compact allocation is deprecated in libttorrent, and will
be removed in future versions.</p>
<p>The compact allocation will only allocate as much storage as it needs to keep the
pieces downloaded so far. This means that pieces will be moved around to be placed
at their final position in the files while downloading (to make sure the completed
download has all its pieces in the correct place). So, the main drawbacks are:</p>
<blockquote>
<ul class="simple">
<li>More disk operations while downloading since pieces are moved around.</li>
<li>Potentially more fragmentation in the filesystem.</li>
<li>Cannot be used while having files with priority 0.</li>
</ul>
</blockquote>
<p>The benefits though, are:</p>
<blockquote>
<ul class="simple">
<li>No startup delay, since the files don't need allocating.</li>
<li>The download will not use unnecessary disk space.</li>
<li>Disk caches perform much better than in full allocation and raises the download
speed limit imposed by the disk.</li>
<li>Works well on filesystems that don't support sparse files.</li>
</ul>
</blockquote>
<p>The algorithm that is used when allocating pieces and slots isn't very complicated.
For the interested, a description follows.</p>
<p>storing a piece:</p>
<ol class="arabic simple">
<li>let <strong>A</strong> be a newly downloaded piece, with index <strong>n</strong>.</li>
<li>let <strong>s</strong> be the number of slots allocated in the file we're
downloading to. (the number of pieces it has room for).</li>
<li>if <strong>n</strong> &gt;= <strong>s</strong> then allocate a new slot and put the piece there.</li>
<li>if <strong>n</strong> &lt; <strong>s</strong> then allocate a new slot, move the data at
slot <strong>n</strong> to the new slot and put <strong>A</strong> in slot <strong>n</strong>.</li>
</ol>
<p>allocating a new slot:</p>
<ol class="arabic simple">
<li>if there's an unassigned slot (a slot that doesn't
contain any piece), return that slot index.</li>
<li>append the new slot at the end of the file (or find an unused slot).</li>
<li>let <strong>i</strong> be the index of newly allocated slot</li>
<li>if we have downloaded piece index <strong>i</strong> already (to slot <strong>j</strong>) then<ol class="arabic">
<li>move the data at slot <strong>j</strong> to slot <strong>i</strong>.</li>
<li>return slot index <strong>j</strong> as the newly allocated free slot.</li>
</ol>
</li>
<li>return <strong>i</strong> as the newly allocated slot.</li>
</ol>
</div>
</div>
<div class="section" id="extensions">
<h1>extensions</h1>
<p>These extensions all operates within the <a class="reference external" href="extension_protocol.html">extension protocol</a>. The
name of the extension is the name used in the extension-list packets,
and the payload is the data in the extended message (not counting the
length-prefix, message-id nor extension-id).</p>
<p>Note that since this protocol relies on one of the reserved bits in the
handshake, it may be incompatible with future versions of the mainline
bittorrent client.</p>
<p>These are the extensions that are currently implemented.</p>
<div class="section" id="metadata-from-peers">
<h2>metadata from peers</h2>
<p>Extension name: &quot;LT_metadata&quot;</p>
<p>This extension is deprecated in favor of the more widely supported <tt class="docutils literal">ut_metadata</tt>
extension, see <a class="reference external" href="http://bittorrent.org/beps/bep_0009.html">BEP 9</a>.
The point with this extension is that you don't have to distribute the
metadata (.torrent-file) separately. The metadata can be distributed
through the bittorrent swarm. The only thing you need to download such
a torrent is the tracker url and the info-hash of the torrent.</p>
<p>It works by assuming that the initial seeder has the metadata and that
the metadata will propagate through the network as more peers join.</p>
<p>There are three kinds of messages in the metadata extension. These packets
are put as payload to the extension message. The three packets are:</p>
<blockquote>
<ul class="simple">
<li>request metadata</li>
<li>metadata</li>
<li>don't have metadata</li>
</ul>
</blockquote>
<p>request metadata:</p>
<table border="1" class="docutils">
<colgroup>
<col width="17%" />
<col width="23%" />
<col width="61%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">size</th>
<th class="head">name</th>
<th class="head">description</th>
</tr>
</thead>
<tbody valign="top">
<tr><td>uint8_t</td>
<td>msg_type</td>
<td>Determines the kind of message this is
0 means 'request metadata'</td>
</tr>
<tr><td>uint8_t</td>
<td>start</td>
<td>The start of the metadata block that
is requested. It is given in 256:ths
of the total size of the metadata,
since the requesting client don't know
the size of the metadata.</td>
</tr>
<tr><td>uint8_t</td>
<td>size</td>
<td>The size of the metadata block that is
requested. This is also given in
256:ths of the total size of the
metadata. The size is given as size-1.
That means that if this field is set
0, the request wants one 256:th of the
metadata.</td>
</tr>
</tbody>
</table>
<p>metadata:</p>
<table border="1" class="docutils">
<colgroup>
<col width="17%" />
<col width="23%" />
<col width="61%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">size</th>
<th class="head">name</th>
<th class="head">description</th>
</tr>
</thead>
<tbody valign="top">
<tr><td>uint8_t</td>
<td>msg_type</td>
<td>1 means 'metadata'</td>
</tr>
<tr><td>int32_t</td>
<td>total_size</td>
<td>The total size of the metadata, given
in number of bytes.</td>
</tr>
<tr><td>int32_t</td>
<td>offset</td>
<td>The offset of where the metadata block
in this message belongs in the final
metadata. This is given in bytes.</td>
</tr>
<tr><td>uint8_t[]</td>
<td>metadata</td>
<td>The actual metadata block. The size of
this part is given implicit by the
length prefix in the bittorrent
protocol packet.</td>
</tr>
</tbody>
</table>
<p>Don't have metadata:</p>
<table border="1" class="docutils">
<colgroup>
<col width="17%" />
<col width="23%" />
<col width="61%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">size</th>
<th class="head">name</th>
<th class="head">description</th>
</tr>
</thead>
<tbody valign="top">
<tr><td>uint8_t</td>
<td>msg_type</td>
<td>2 means 'I don't have metadata'.
This message is sent as a reply to a
metadata request if the the client
doesn't have any metadata.</td>
</tr>
</tbody>
</table>
</div>
<div class="section" id="dont-have">
<h2>dont_have</h2>
<p>Extension name: &quot;lt_dont_have&quot;</p>
<p>The <tt class="docutils literal">dont_have</tt> extension message is used to tell peers that the client no longer
has a specific piece. The extension message should be advertised in the <tt class="docutils literal">m</tt> dictionary
as <tt class="docutils literal">lt_dont_have</tt>. The message format mimics the regular <tt class="docutils literal">HAVE</tt> bittorrent message.</p>
<p>Just like all extension messages, the first 2 bytes in the mssage itself are 20 (the
bittorrent extension message) and the message ID assigned to this extension in the <tt class="docutils literal">m</tt>
dictionary in the handshake.</p>
<table border="1" class="docutils">
<colgroup>
<col width="17%" />
<col width="23%" />
<col width="61%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">size</th>
<th class="head">name</th>
<th class="head">description</th>
</tr>
</thead>
<tbody valign="top">
<tr><td>uint32_t</td>
<td>piece</td>
<td>index of the piece the peer no longer
has.</td>
</tr>
</tbody>
</table>
<p>The length of this message (including the extension message prefix) is
6 bytes, i.e. one byte longer than the normal <tt class="docutils literal">HAVE</tt> message, because
of the extension message wrapping.</p>
</div>
<div class="section" id="http-seeding">
<h2>HTTP seeding</h2>
<p>There are two kinds of HTTP seeding. One with that assumes a smart
(and polite) client and one that assumes a smart server. These
are specified in <a class="reference external" href="http://bittorrent.org/beps/bep_0019.html">BEP 19</a> and <a class="reference external" href="http://bittorrent.org/beps/bep_0017.html">BEP 17</a> respectively.</p>
<p>libtorrent supports both. In the libtorrent source code and API,
BEP 19 urls are typically referred to as <em>url seeds</em> and BEP 17
urls are typically referred to as <em>HTTP seeds</em>.</p>
<p>The libtorrent implementation of <a class="reference external" href="http://bittorrent.org/beps/bep_0019.html">BEP 19</a> assumes that, if the URL ends with a slash
('/'), the filename should be appended to it in order to request pieces from
that file. The way this works is that if the torrent is a single-file torrent,
only that filename is appended. If the torrent is a multi-file torrent, the
torrent's name '/' the file name is appended. This is the same directory
structure that libtorrent will download torrents into.</p>
</div>
</div>
<div class="section" id="piece-picker">
<h1>piece picker</h1>
<p>The piece picker in libtorrent has the following features:</p>
<ul class="simple">
<li>rarest first</li>
<li>sequential download</li>
<li>random pick</li>
<li>reverse order picking</li>
<li>parole mode</li>
<li>prioritize partial pieces</li>
<li>prefer whole pieces</li>
<li>piece affinity by speed category</li>
<li>piece priorities</li>
</ul>
<div class="section" id="internal-representation">
<h2>internal representation</h2>
<p>It is optimized by, at all times, keeping a list of pieces ordered
by rarity, randomly shuffled within each rarity class. This list
is organized as a single vector of contigous memory in RAM, for
optimal memory locality and to eliminate heap allocations and frees
when updating rarity of pieces.</p>
<p>Expensive events, like a peer joining or leaving, are evaluated
lazily, since it's cheaper to rebuild the whole list rather than
updating every single piece in it. This means as long as no blocks
are picked, peers joining and leaving is no more costly than a single
peer joining or leaving. Of course the special cases of peers that have
all or no pieces are optimized to not require rebuilding the list.</p>
</div>
<div class="section" id="picker-strategy">
<h2>picker strategy</h2>
<p>The normal mode of the picker is of course <em>rarest first</em>, meaning
pieces that few peers have are preferred to be downloaded over pieces
that more peers have. This is a fundamental algorithm that is the
basis of the performance of bittorrent. However, the user may set the
piece picker into sequential download mode. This mode simply picks
pieces sequentially, always preferring lower piece indices.</p>
<p>When a torrent starts out, picking the rarest pieces means increased
risk that pieces won't be completed early (since there are only a few
peers they can be downloaded from), leading to a delay of having any
piece to offer to other peers. This lack of pieces to trade, delays
the client from getting started into the normal tit-for-tat mode of
bittorrent, and will result in a long ramp-up time. The heuristic to
mitigate this problem is to, for the first few pieces, pick random pieces
rather than rare pieces. The threshold for when to leave this initial
picker mode is determined by <tt class="docutils literal"><span class="pre">session_settings::initial_picker_threshold</span></tt>.</p>
</div>
<div class="section" id="reverse-order">
<h2>reverse order</h2>
<p>An orthogonal setting is <em>reverse order</em>, which is used for <em>snubbed</em>
peers. Snubbed peers are peers that appear very slow, and might have timed
out a piece request. The idea behind this is to make all snubbed peers
more likely to be able to do download blocks from the same piece,
concentrating slow peers on as few pieces as possible. The reverse order
means that the most common pieces are picked, instead of the rarest pieces
(or in the case of sequential download, the last pieces, intead of the first).</p>
</div>
<div class="section" id="parole-mode">
<h2>parole mode</h2>
<p>Peers that have participated in a piece that failed the hash check, may be
put in <em>parole mode</em>. This means we prefer downloading a full piece  from this
peer, in order to distinguish which peer is sending corrupt data. Whether to
do this is or not is controlled by <tt class="docutils literal"><span class="pre">session_settings::use_parole_mode</span></tt>.</p>
<p>In parole mode, the piece picker prefers picking one whole piece at a time for
a given peer, avoiding picking any blocks from a piece any other peer has
contributed to (since that would defeat the purpose of parole mode).</p>
</div>
<div class="section" id="prioritize-partial-pieces">
<h2>prioritize partial pieces</h2>
<p>This setting determines if partially downloaded or requested pieces should always
be preferred over other pieces. The benefit of doing this is that the number of
partial pieces is minimized (and hence the turn-around time for downloading a block
until it can be uploaded to others is minimized). It also puts less stress on the
disk cache, since fewer partial pieces need to be kept in the cache. Whether or
not to enable this is controlled by <tt class="docutils literal"><span class="pre">session_settings::prioritize_partial_pieces</span></tt>.</p>
<p>The main benefit of not prioritizing partial pieces is that the rarest first
algorithm gets to have more influence on which pieces are picked. The picker is
more likely to truly pick the rarest piece, and hence improving the performance
of the swarm.</p>
<p>This setting is turned on automatically whenever the number of partial pieces
in the piece picker exceeds the number of peers we're connected to times 1.5.
This is in order to keep the waste of partial pieces to a minimum, but still
prefer rarest pieces.</p>
</div>
<div class="section" id="prefer-whole-pieces">
<h2>prefer whole pieces</h2>
<p>The <em>prefer whole pieces</em> setting makes the piece picker prefer picking entire
pieces at a time. This is used by web connections (both http seeding
standards), in order to be able to coalesce the small bittorrent requests
to larger HTTP requests. This significantly improves performance when
downloading over HTTP.</p>
<p>It is also used by peers that are downloading faster than a certain
threshold. The main advantage is that these peers will better utilize the
other peer's disk cache, by requesting all blocks in a single piece, from
the same peer.</p>
<p>This threshold is controlled by <tt class="docutils literal"><span class="pre">session_settings::whole_pieces_threshold</span></tt>.</p>
<p><em>TODO: piece affinity by speed category</em>
<em>TODO: piece priorities</em></p>
</div>
</div>
<div class="section" id="ssl-torrents">
<h1>SSL torrents</h1>
<p>Torrents may have an SSL root (CA) certificate embedded in them. Such torrents
are called <em>SSL torrents</em>. An SSL torrent talks to all bittorrent peers over SSL.
The protocols are layered like this:</p>
<pre class="literal-block">
+-----------------------+
| BitTorrent protocol   |
+-----------------------+
| SSL                   |
+-----------+-----------+
| TCP       | uTP       |
|           +-----------+
|           | UDP       |
+-----------+-----------+
</pre>
<p>During the SSL handshake, both peers need to authenticate by providing a certificate
that is signed by the CA certificate found in the .torrent file. These peer
certificates are expected to be privided to peers through some other means than
bittorrent. Typically by a peer generating a certificate request which is sent to
the publisher of the torrent, and the publisher returning a signed certificate.</p>
<p>In libtorrent, <a class="reference internal" href="#set-ssl-certificate">set_ssl_certificate()</a> in <a class="reference internal" href="#torrent-handle">torrent_handle</a> is used to tell libtorrent where
to find the peer certificate and the private key for it. When an SSL torrent is loaded,
the <a class="reference internal" href="#torrent-need-cert-alert">torrent_need_cert_alert</a> is posted to remind the user to provide a certificate.</p>
<p>A peer connecting to an SSL torrent MUST provide the <em>SNI</em> TLS extension (server name
indication). The server name is the hex encoded info-hash of the torrent to connect to.
This is required for the client accepting the connection to know which certificate to
present.</p>
<p>SSL connections are accepted on a separate socket from normal bittorrent connections. To
pick which port the SSL socket should bind to, set <tt class="docutils literal"><span class="pre">session_settings::ssl_listen</span></tt> to a
different port. It defaults to port 4433. This setting is only taken into account when the
normal listen socket is opened (i.e. just changing this setting won't necessarily close
and re-open the SSL socket). To not listen on an SSL socket at all, set <tt class="docutils literal">ssl_listen</tt> to 0.</p>
<p>This feature is only available if libtorrent is build with openssl support (<tt class="docutils literal">TORRENT_USE_OPENSSL</tt>)
and requires at least openSSL version 1.0, since it needs SNI support.</p>
<p>Peer certificates must have at least one <em>SubjectAltName</em> field of type dNSName. At least
one of the fields must <em>exactly</em> match the name of the torrent. This is a byte-by-byte comparison,
the UTF-8 encoding must be identical (i.e. there's no unicode normalization going on). This is
the recommended way of verifying certificates for HTTPS servers according to <a class="reference external" href="http://www.ietf.org/rfc/rfc2818.txt">RFC 2818</a>. Note
the difference that for torrents only <em>dNSName</em> fields are taken into account (not IP address fields).
The most specific (i.e. last) <em>Common Name</em> field is also taken into account if no <em>SubjectAltName</em>
did not match.</p>
<p>If any of these fields contain a single asterisk (&quot;*&quot;), the certificate is considered covering
any torrent, allowing it to be reused for any torrent.</p>
<p>The purpose of matching the torrent name with the fields in the peer certificate is to allow
a publisher to have a single root certificate for all torrents it distributes, and issue
separate peer certificates for each torrent. A peer receiving a certificate will not necessarily
be able to access all torrents published by this root certificate (only if it has a &quot;star cert&quot;).</p>
<div class="section" id="testing">
<h2>testing</h2>
<p>To test incoming SSL connections to an SSL torrent, one can use the following <em>openssl</em> command:</p>
<pre class="literal-block">
openssl s_client -cert &lt;peer-certificate&gt;.pem -key &lt;peer-private-key&gt;.pem -CAfile &lt;torrent-cert&gt;.pem -debug -connect 127.0.0.1:4433 -tls1 -servername &lt;info-hash&gt;
</pre>
<p>To create a root certificate, the Distinguished Name (<em>DN</em>) is not taken into account
by bittorrent peers. You still need to specify something, but from libtorrent's point of
view, it doesn't matter what it is. libtorrent only makes sure the peer certificates are
signed by the correct root certificate.</p>
<p>One way to create the certificates is to use the <tt class="docutils literal">CA.sh</tt> script that comes with openssl, like thisi (don't forget to enter a common Name for the certificate):</p>
<pre class="literal-block">
CA.sh -newca
CA.sh -newreq
CA.sh -sign
</pre>
<p>The torrent certificate is located in <tt class="docutils literal">./demoCA/private/demoCA/cacert.pem</tt>, this is
the pem file to include in the .torrent file.</p>
<p>The peer's certificate is located in <tt class="docutils literal">./newcert.pem</tt> and the certificate's
private key in <tt class="docutils literal">./newkey.pem</tt>.</p>
</div>
</div>
    </div>
    <div id="footer">
    <span>Copyright &copy; 2005 Rasterbar Software.</span>
    </div>
    </div>
    <script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
    </script>
    <script type="text/javascript">
    _uacct = "UA-1599045-1";
    urchinTracker();
    </script>
</div>
</body>
</html>
